[英]How do I change the background color of a button within a custom UITableViewCell programatically in Swift?
我有一个自定义的UITableViewCell
,它的子视图之一是一个button
(标题为“RSVP”):
它连接到以下代码:
class SelectedEventsTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var attendanceLabel: UILabel!
@IBOutlet weak var attendanceButton: UIButton!
}
我试图通过将此代码添加到SelectedEventsTableViewCell
class 来更改按钮的背景颜色:
override func awakeFromNib() {
super.awakeFromNib()
attendanceButton.backgroundColor = UIColor.greenColor()
}
但是,它不起作用。 该按钮获得白色背景:
有人知道为什么会这样吗? 当我在按下按钮时以编程方式设置按钮的背景颜色时,它也不起作用。
感谢您的帮助。
检查某处您将按钮背景色设置为白色。
attendanceButton.backgroundColor = UIColor.whiteColor()
检查在TableView的数据源中使用SelectedEventsTableViewCell的对象的位置,或在viewController中使用委托方法的位置。
例如
cell.attendanceButton.backgroundColor = UIColor.whiteColor()
有几种可能的原因。
1.您是否可以使用该插座? 如果不是,请从情节提要中按CTRL-DRAG。
2.您在awakeFromNib()
之后更改了吗? 也许您可以在cellForIndexPath
(表视图数据源)中再次进行设置。
3.Cell被重用但醒了一次。 这意味着您应该在重用后恢复其状态。 prepareForReuse()
为此目的而设计。
我知道这个问题很老,但我在 iOS 15 上遇到了同样的事情。解决方案是使用新的UIButton.Configuration
结构。
if #available(iOS 15.0, *) {
var config = UIButton.Configuration.filled()
config.baseBackgroundColor = UIColor.greenColor()
attendanceButton.configuration = config
} else {
attendanceButton.backgroundColor = UIColor.greenColor()
}
在您的prepareForReuse
function 中运行类似的东西,或者在您将单元格出队之后,它应该会再次开始工作。 iOS 15 中有更多自定义选项使用该配置结构,因此请深入了解它以配置按钮的所有其他方面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.