gpt4 book ai didi

ios - 如何在 iOS swift4 中更改特定的 UITableviewcell 颜色

转载 作者:行者123 更新时间:2023-11-28 09:48:54 25 4
gpt4 key购买 nike

我有两个数组,比如

names  = ["Gopal", "Harish", "Kartik","Raj", "Vishal", "Manoj", "James"] 
StoredNames = ["kartik", "Vishal", "James"]

我正在将名称数组显示到 TableView 中。但我的任务是,如果名称数组包含 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 语句是必需的。变量名也应该是 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()) {

关于ios - 如何在 iOS swift4 中更改特定的 UITableviewcell 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53477563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com