Ios Can';t更改静态单元格中UILabel的背景色
我有一个带有静态单元格的表视图。在那里,我选择了样式Ios Can';t更改静态单元格中UILabel的背景色,ios,swift,xcode,uilabel,Ios,Swift,Xcode,Uilabel,我有一个带有静态单元格的表视图。在那里,我选择了样式右细节 现在我想更改右侧的细节标签的背景色。即使它只是一个标签,我也无法更改IB中的背景颜色 所以我把它拉到一个视图控制器中,以编程的方式完成它 @IBOutlet weak var ukPremiumLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() ukPremiumLabel.layer.backgroundColor = U
右细节
现在我想更改右侧的细节标签的背景色。即使它只是一个标签,我也无法更改IB中的背景颜色
所以我把它拉到一个视图控制器中,以编程的方式完成它
@IBOutlet weak var ukPremiumLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
ukPremiumLabel.layer.backgroundColor = UIColor(red: 0/255, green: 159/255, blue: 184/255, alpha: 1.0).cgColor
}
我也这样试过:
override func viewDidLoad() {
super.viewDidLoad()
ukPremiumLabel.backgroundColor = UIColor.blue
}
我不知道为什么它仍然是白色的
您使用的是内置的UITableViewCell
样式,因此在创建单元格后,单元格的detailTextLabel
的backgroundColor
会以某种方式被覆盖
您可以通过在颜色属性已更改后更改该属性来解决此问题
为此,您可以在您的UITableViewController的overridedwillDisplay
方法中更改此颜色
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.detailTextLabel == ukPremiumLabel {
ukPremiumLabel.backgroundColor = .blue
}
}
您可以为UILabel
使用IBDesignable/IBInspectable
注释
@IBDesignable
class BackgroundLabel: UILabel {
@IBInspectable var persistentBackgroundColor: UIColor = UIColor.red {
didSet {
super.backgroundColor = persistentBackgroundColor
}
}
override var backgroundColor: UIColor? {
didSet {
if backgroundColor != persistentBackgroundColor {
backgroundColor = persistentBackgroundColor
}
}
}
}
并在UITableViewCell
中为detailtextlab
分配BackgroundLabel
试试看。你会感到惊讶的。它完全忽略了它,因为它也是以编程方式进行的。似乎detailTextLabel
以某种方式被覆盖。但公认的解决方案是有效的。对,我现在明白了。这是因为您使用了内置样式。我为什么要使用willdisplay委托?如果您使用的是静态单元格,则不必对任何内容使用cellForRowAt
方法,因此在willDisplay
中更改它更容易(您必须获取单元格的引用,在willDisplay
中,您将单元格的引用作为方法的参数)。另外,willDisplay
非常适合进行“装饰性”更改()