前提
カスタムセルの中にViewを配置し背景色を付けたいです。
実現したいこと
該当のソースコード
swift
1 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 2 3// 省略 4let iconColors = ["FF0000", "00E676", "3E96FD", "FF8157"] 5 6cell.colorIcon.backgroundColor = UIColor(hex: iconColors[indexPath.row]) 7 8 return cell 9} 10 11// MARK: - Action 12@IBAction func AddButton(_ sender: Any) { 13 14 var uiTextField = UITextField() 15 let ac = UIAlertController(title: "データ", message: "", preferredStyle: .alert) 16 let aa = UIAlertAction(title: "OK", style: .default) { (action) in 17 18 if uiTextField.text == "" {return} 19 20 // 配列に追加 21 self.textFieldStringList.append(uiTextField.text!) 22 // テーブル更新 23 self.tableView.reloadData() 24 // UserDefaultsに保存 25 UserDefaults.standard.set(self.textFieldStringList, forKey: "StringList") 26 print(uiTextField.text!) 27 } 28 ac.addTextField { (textField) in 29 textField.placeholder = "入力してください" 30 uiTextField = textField 31 } 32 ac.addAction(aa) 33 present(ac, animated: true, completion: nil) 34 }
発生している問題・エラーメッセージ
ボタンを押下するとエラーで落ちます。
Fatal error: Index out of range 致命的なエラー:インデックスが範囲外です
試したこと
・How to change each uitableviewcell background color
https://stackoverflow.com/questions/38845948/how-to-change-each-uitableviewcell-background-color
swift
1/* 色が反映されませんでした */ 2private func tableView(tableView: UITableView, willDisplayCell cell: NormalTableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 3 let iconColors = ["FF0000", "00E676", "3E96FD", "FF8157"] 4 cell.colorIcon.backgroundColor = UIColor(hex: iconColors[indexPath.row % textFieldString.count]) 5 } 6
cellの背景色をカラフルにする方法が知りたいです
よろしくお願いします
Index out of range エラーはどこで出ますか? cellForRowAt で iconColors は 4 つしかないのに、セルが 5 個以上になってるとか?
> Index out of range エラーはどこで出ますか?
cell.colorIcon.backgroundColor = UIColor(hex: iconColors[indexPath.row]) の行で出ています。
> cellForRowAt で iconColors は 4 つしかないのに、セルが 5 個以上になってるとか?
おしゃる通りです
4つ以上の場合はfor文で回すのでしょうか??
ごめんなさい、見落としてましたが、セルが 5 個以上の場合はその 4 色を繰り返したいんですね。その場合、
iconColors[indexPath.row % textFieldString.count] じゃなくて
iconColors[indexPath.row % iconColors.count] とする必要があるかと。
ありがとうございます。
無事解決しました。
回答1件