UIButton不会改变标题

时间:2016-07-13 16:44:41

标签: swift

我想在点击按钮时更改按钮标题:

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)
    }
}

1 个答案:

答案 0 :(得分:2)

问题是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)
}