[英]How to change a label text color when pressed on a table view with swift?
I have a UITableView
with a cell that has 1 UILabel
in it. 我有一个带有一个
UILabel
的单元格的UITableView
。 I want the cell labels text color to change when the cell is pressed. 我希望单元格标签的文本颜色在单元格被按下时改变。 How do I do that?
我怎么做?
This is what I tried: 这是我尝试的:
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()
}
Subclass UITableViewCell and overwrite setSelected. 子类化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()
}
}
Implement the didDeselectRowAtIndexPath delegate method. 实现didDeselectRowAtIndexPath委托方法。 In this method you should set the label back to the normal color.
在这种方法中,您应该将标签重新设置为正常颜色。
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()
}
Also, remove .reloadInputViews() unless you actually need it. 此外,除非确实需要,否则请删除.reloadInputViews()。 This is probably wiping any updating of textColor.
这可能抹去了textColor的任何更新。
Swift 3 version looks like: 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
}
}
just mention that this is much clear and better way to do it than in didSelectRowAtIndexPath 只需提一下,这是比didSelectRowAtIndexPath更清晰,更好的方法
What I generally uses for such situations is overriding setHighlighted
in UITableViewCell
subclass as: 我通常在这种情况下使用的是
setHighlighted
UITableViewCell
子类中的setHighlighted
重写为:
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
label.textColor = UIColor.redColor()
}
For this, you have to use custom table view cells to override particular method. 为此,您必须使用自定义表格视图单元格覆盖特定方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.