Swift如何设置单个TableViewCell的颜色?

时间:2017-09-23 15:08:09

标签: swift tableview cell

我试过

if(indexPath.row == colorIndex){
   cell.textLabel?.textColor = UIColor.red
}

和这个

func setup(item: MPMediaItem){
    self.textLabel?.text = item.value(forProperty: MPMediaItemPropertyTitle) as? String
    if(currentPlayingItem == item){
        self.textLabel?.textColor = UIColor.red
    }
}

这是我的自定义UITableCell类中的一个方法

但正如你在GIF上看到的那样,其他细胞也会受到影响。我怎样才能避免这种情况,只有索引的那个,比方说3会变色?

enter image description here

2 个答案:

答案 0 :(得分:2)

专门将非红色行设置为黑色(或任何非红色行):

if(indexPath.row == colorIndex){
    cell.textLabel?.textColor = UIColor.red
}
else {
    cell.textLabel?.textColor = UIColor.black
}

答案 1 :(得分:1)

如果您希望特定数据是彩色的,那么此color attribute应该在数据本身中。

struct Item {
  ... // other members 
  var preferredColor:UIColor? // I'd use hex instead so you could transform your hex code to UIColor 
}

var items = [Item]() // array 

// cellForRowAt
let dataAtCell = items[indexPath.row]

cell.textLabel?.textColor = dataAtCell.preferredColor ?? .black // if you don't have a color for that cell then the default color is black