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

时间:2018-11-26 08:56:22

标签: ios iphone swift

我有两个数组

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

我在表视图中显示名称Array。但是我的任务是如果名称数组包含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
    }
}

2 个答案:

答案 0 :(得分:4)

您可以使用contains(element)。请记住,由于reusable functionality,需要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()) {

答案 1 :(得分:1)

请在indepath的cellforrow中使用此

if(indexPath.row % 2 == 0) {
    cell.backgroundColor = UIColor.init(rgb: 0xebebeb)
} else{
    cell.backgroundColor = UIColor.init(rgb: 0xdcdcdc)
}