2014-09-13 145 views
8

我想以編程方式更改具有歸屬標題的UIButton的標題。 該按鈕在IB中創建。我不想只改變標題/文本的屬性。以編程方式更改UIButton的屬性標題

我試過下面的代碼,但找不到方法來更改NSAttributedString的標題。

NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal]; 

// How can I change title of attributedString without changing the attributes? 

[self.deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

謝謝!

回答

15

部分你有答案。

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]]; 

[attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"]; 

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 

而不是創造NSAttributedString創建NSMutableAttributedString那麼你可以這樣設置字符串。

2

這真的取決於你的attributedString:

  • 「純」 attributedString: 這意味着你的attrString只有1套適用於字符串的整個長度的屬性。在這種情況下,您可以執行以下操作:

    NSAttributedString *attrString = WHATEVER; 
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL]; 
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER 
                        attributes:attributes]; 
    
  • 您attributedString有屬性的不同範圍:
    這取決於你attributedString的結構得到非常複雜,因爲你必須做很多的範圍處理等。在這種情況下,您最好創建一個新的NSMutableAttributedString並從頭開始設置屬性。

4

斯威夫特3回答:

if let attributedTitle = yourButton.attributedTitle(for: .normal) { 
    let mutableAttributedTitle = NSMutableAttributedString(attributedString: attributedTitle) 
    mutableAttributedTitle.replaceCharacters(in: NSMakeRange(0, mutableAttributedTitle.length), with: "New title") 
    yourButton.setAttributedTitle(mutableAttributedTitle, for: .normal) 
}