簡體   English   中英

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

[英]How to change particular UITableviewcell colour in iOS swift4

我有兩個數組

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) 請記住,由於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()) {

請在indepath的cellforrow中使用它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM