簡體   English   中英

快速在表格視圖上按下時如何更改標簽文本的顏色?

[英]How to change a label text color when pressed on a table view with swift?

我有一個帶有一個UILabel的單元格的UITableView 我希望單元格標簽的文本顏色在單元格被按下時改變。 我怎么做?

這是我嘗試的:

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        let cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell

        let label:UILabel = cell.viewWithTag(1) as UILabel
        label.textColor = UIColor(red: 46/255.0, green: 204/255.0, blue: 113/255.0, alpha: 1.0)
        cell.reloadInputViews()



    }

子類化UITableViewCell並覆蓋setSelected。

@IBOutlet weak var label: UILabel!
override func setSelected(selected: Bool, animated: Bool) {
  if (selected) {
    label.textColor = UIColor.redColor()
  } else {
    label.textColor = UIColor.blackColor()
  }
}

實現didDeselectRowAtIndexPath委托方法。 在這種方法中,您應該將標簽重新設置為正常顏色。

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
  let cell = tableView.cellForRowAtIndexPath(indexPath)
  let label: UILabel = cell.viewWithTag(1) as UILabel
  label.textColor = UIColor.redColor()
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
  let cell = tableView.cellForRowAtIndexPath(indexPath)
  let label: UILabel = cell.viewWithTag(1) as UILabel
  label.textColor = UIColor.blackColor()
}

此外,除非確實需要,否則請刪除.reloadInputViews()。 這可能抹去了textColor的任何更新。

Swift 3版本如下所示:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if (selected) {
         self.artistLabel.textColor = UIColor.lightGray
    } else {
         self.artistLabel.textColor = UIColor.black
    }
}

只需提一下,這是比didSelectRowAtIndexPath更清晰,更好的方法

我通常在這種情況下使用的是setHighlighted UITableViewCell子類中的setHighlighted重寫為:

override func setHighlighted(_ highlighted: Bool, animated: Bool) {
    super.setHighlighted(highlighted, animated: animated)
    label.textColor = UIColor.redColor()
}

為此,您必須使用自定義表格視圖單元格覆蓋特定方法。

暫無
暫無

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

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