ios - 如何在 iOS swift4 中更改特定的 UITableviewcell 颜色
问题描述
我有两个数组
names = ["Gopal", "Harish", "Kartik","Raj", "Vishal", "Manoj", "James"]
StoredNames = ["kartik", "Vishal", "James"]
我正在将名称数组显示到表格视图中。但我的任务是,如果名称数组包含 StoredNames 数组元素,我需要更改特定的单元格颜色。谁能指导我完成这项任务。我使用的是代码。但无法与StoredNames
数组进行比较。
override func tableView(_ tableView: UITableView, willDisplay cell:UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .yellow
if let index = names.index(of: "kartik") {
cell.backgroundColor = indexPath.row == index ? .green : .white
}
return cell
}
编辑后:
func filterRowsForSearchedText(_ searchText: String) {
filteredModels = models.filter({( model : Contact) -> Bool in
return model.name.lowercased().contains(searchText.lowercased())||model.number.lowercased().contains(searchText.lowercased())
})
contactsTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = contactsTableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell", for: indexPath) as! ContactsTableViewCell
let model: Contact
if searchController.isActive && searchController.searchBar.text != "" {
model = filteredModels[indexPath.row]
} else {
model = models[indexPath.row]
}
cell.nameLabel.text = model.name
cell.numberLabel.text = model.number
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if storedNumberArr.contains(numberArr[indexPath.row]) {
//Name is there, color it
cell.backgroundColor = .green
} else {
// Color for non existance.
cell.backgroundColor = .white
}
}
解决方案
您可以使用contains(element)
. 请记住, else 语句是必要的,因为reusable functionality
. 变量名也应该是camelCase
.
let names = ["Gopal","Harish","Kartik","Raj","Vishal","Manoj","James"]
let storedNames = ["kartik","Vishal","James"]
if storedNames.contains(names[indexPath.row]) {
//Name is there, color it
cell.backgroundColor = .green
} else {
// Color for non existance.
cell.backgroundColor = .white
}
正如 dahiya_boy 所建议的,如果你想比较丢弃它们的字符串,cases
你可以在上面替换if-condition
为:
if storedNames.map({ $0.lowercased()}).contains(names[indexPath.row].lowercased()) {
推荐阅读
- python - 从二维数组中获取值以列出行列位置
- html - 使用 PowerShell 在电子邮件中将 excel 表作为正文发送
- git - [新到 git]git push origin master 创建了新的 master 分支。(回购中的默认主)
- r - 根据长度拆分字符向量
- python-3.x - pandas 将两列合并为一个新列
- jquery - ASP.NET Core 5 data-ajax 属性未应用于通过函数提交的表单
- sql - SQL 对不同列的多个查询
- sql-server - SSIS 数据分析任务编辑器返回错误代码
- python - 为什么 Pycharm 在重构时会自动重命名 Jupyter notebook 中的某些方法,而其他方法则不会?
- docker - 使用 k6 docker 映像安装扩展的最佳方式?