[英]Swift Change textColor on Selection
如何更改iOS Swift中选择的label
或cell
的textColor
?
我希望背景不要改变。 只有textColor
和seperatorColor
如果有的话)。 就像是:
label.highlightedTextColor = UIColor.whiteColor();
我已经看到在一些颜色发生变化的应用中会发生这种情况。 但我无法接近它。 根据Apple Dev Reference:
使用标签实现一种文本按钮的子类在绘制按钮的按下状态时可以使用此属性中的值。 只要highlight属性设置为true,此颜色就会自动应用于标签。
但是,标签编译得很好,并且不会在高光上改变颜色。 按钮没有highlightedTextColor
我已经尝试在didSelectAtIndexPath
和didDeselectAtIndexPath
设置它,但颜色随着延迟而变化。 我不喜欢那样。
这就是我最终解决问题的方法:
我已将UITableViewCell
子类化并连接了所有@IBOutlet
。 在awakeFromNib()
我只是这样做:
@IBOutlet weak var myLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.myLabel.highlightedTextColor = .blackColor()
}
现在完美运作!
顺便说一下这是我关于堆栈溢出的第一个答案,请对我好😊嘿嘿
(我使用的是Swift 2.0和Xcode 7.2.1)
您可以在didSelectAtIndexPath
和didDeselectAtIndexPath
以及cellForRowAtIndexPath
设置颜色
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.textColor = UIColor.blackColor()
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.textColor = UIColor.redColor()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue cell
cell.textLabel?.textColor = UIColor.redColor()
}
如果您(使用/不使用)自定义单元格(作为xib),您可以选择标签,并从实用程序转到突出显示并将颜色更改为您要在选择中显示的颜色。 这是一个更清晰的快照:)
在cellForRowAt
indexPath
您只需添加此行即可
cell.textLabel?.textColor = UIColor.blackColor()
在方法setSelected的单元格本身中,您可以覆盖它,然后提供您想要的任何颜色或突出显示的状态:
override func setSelected(_ selected:Bool,animated:Bool){super.setSelected(selected,animated:animated)
if isSelected {
// your color or highlited here
} else {
// your colour or highlighted here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.