前提
カスタムセルの中にViewを配置し背景色を付けたいです。
実現したいこと
該当のソースコード
swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 省略 let iconColors = ["FF0000", "00E676", "3E96FD", "FF8157"] cell.colorIcon.backgroundColor = UIColor(hex: iconColors[indexPath.row]) return cell } // MARK: - Action @IBAction func AddButton(_ sender: Any) { var uiTextField = UITextField() let ac = UIAlertController(title: "データ", message: "", preferredStyle: .alert) let aa = UIAlertAction(title: "OK", style: .default) { (action) in if uiTextField.text == "" {return} // 配列に追加 self.textFieldStringList.append(uiTextField.text!) // テーブル更新 self.tableView.reloadData() // UserDefaultsに保存 UserDefaults.standard.set(self.textFieldStringList, forKey: "StringList") print(uiTextField.text!) } ac.addTextField { (textField) in textField.placeholder = "入力してください" uiTextField = textField } ac.addAction(aa) present(ac, animated: true, completion: nil) }
発生している問題・エラーメッセージ
ボタンを押下するとエラーで落ちます。
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
/* 色が反映されませんでした */ private func tableView(tableView: UITableView, willDisplayCell cell: NormalTableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let iconColors = ["FF0000", "00E676", "3E96FD", "FF8157"] cell.colorIcon.backgroundColor = UIColor(hex: iconColors[indexPath.row % textFieldString.count]) }
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] とする必要があるかと。
ありがとうございます。
無事解決しました。
まだ回答がついていません
会員登録して回答してみよう