簡體   English   中英

Swift如何設置單個TableViewCell的顏色?

[英]Swift How to set color of a single 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 

暫無
暫無

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

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