2016-07-13 85 views
0

我想更改按鈕標題上點擊按鈕:的UIButton沒有改變標題

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

我的這種問題的方法是儘可能簡化代碼並逐漸重新引入代碼行。你有沒有嘗試過'UIView.setAnimationsEnabled'調用? –

+0

我現在發現克恩函數是問題。只要我再次禁用它,它就可以工作。但是,爲什麼在使用它時不刷新文本? – sesc360

+0

看看我的答案,我測試了一下。 –

回答

2

的問題是,self.titleLabel.text屬性獲取在以下佈局過程中更新。這就是爲什麼你通過setTitle(:forState:)函數設置標題,而不是直接標籤。在你的克恩函數中,當它仍然沒有更新時,它會引用它。請嘗試以下操作:

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

真棒..謝謝! – sesc360