Swift如何设置单个TableViewCell的颜色?
问题描述:
我试图Swift如何设置单个TableViewCell的颜色?
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变得有颜色?
答
具体的非红色行设置为黑色(或任何非红色的颜色是):
if(indexPath.row == colorIndex){
cell.textLabel?.textColor = UIColor.red
}
else {
cell.textLabel?.textColor = UIColor.black
}
答
如果你想具体的数据进行着色,然后这个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