我想在单击按钮时更改按钮标题:
func dispatchStatusButton(title title:String, backgroundColor:UIColor) {
self.btnDispatchStatus.setTitleWithoutAnimation(title.uppercaseString)
self.btnDispatchStatus.backgroundColor = backgroundColor
self.btnDispatchStatus.kern(2.0)
}
当我调用函数时:
// Set Button
self.dispatchStatusButton(title: "Inaktiv", backgroundColor: UIColor(red: 40.0/255.0, green: 51.0/255.0, blue: 57.0/255.0, alpha: 1.0))
没有任何反应,我觉得我的字距调整功能是原因,但我不明白为什么:
extension UIButton {
func setTitleWithoutAnimation(title:String?) {
UIView.setAnimationsEnabled(false)
setTitle(title, forState: .Normal)
layoutIfNeeded()
UIView.setAnimationsEnabled(true)
}
func kern(kerningValue:CGFloat) {
let attributedText = NSAttributedString(string: self.titleLabel!.text!, attributes: [NSKernAttributeName:kerningValue, NSFontAttributeName:self.titleLabel!.font, NSForegroundColorAttributeName:self.titleLabel!.textColor])
self.setAttributedTitle(attributedText, forState: UIControlState.Normal)
}
}
最佳答案
问题是 self.titleLabel.text
属性在以下布局过程中得到更新。这就是为什么要通过 setTitle(:forState:)
函数设置标题,而不是直接设置标签。在您的 kern 函数中,您在它仍未更新时引用它。尝试以下操作:
func kern(kerningValue:CGFloat) {
let title = self.titleForState(.Normal) ?? "" // This gets the new value
let attributedText = NSAttributedString(string: title, attributes: [NSKernAttributeName:kerningValue, NSFontAttributeName:self.titleLabel!.font, NSForegroundColorAttributeName:self.titleLabel!.textColor])
self.setAttributedTitle(attributedText, forState: UIControlState.Normal)
}
关于swift - UIButton 不改变标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38357401/