swift - UIButton 不改变标题

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

最佳答案

问题是 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/

相关文章:

ios - Swift/ios/Google map - 添加 UISlider 时出现 "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"

ios - 如何通过 UICollectionViewController (Swift) 中的 didSelectItemAtIndexPath() 方法访问所有单元格

javascript - 将回调/函数从 native 发送到 javascript

swift - Swift 2 中的函数错误处理

ios - 将 React Native iOS 项目扩展到 tvOS - 链接库

ios - 在哪里可以找到选项卡栏 Controller 类?

ios - TextContainer 在更改 UITextView 的边界时不调整大小

ios - Swift 的 Dropbox 核心 API :Cannot initialize DBSession?

swift - 将字符串文本转换为变量名?

swift - IBOutlet UIButton SIGABRT