簡體   English   中英

以編程方式更改 UIButton 的屬性標題

[英]Programmatically change attributed title of UIButton

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

我已經嘗試了下面的代碼,但找不到更改NSAttributedString標題的NSAttributedString

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

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

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

謝謝!

部分你有答案。

 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然后你可以像這樣設置字符串。

斯威夫特 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)
}

這真的取決於你的屬性字符串:

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

     NSAttributedString *attrString = WHATEVER; NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL]; NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER attributes:attributes];
  • 您的屬性字符串具有不同的屬性范圍:
    這可能會變得非常復雜,具體取決於您的屬性字符串的結構,因為您必須進行大量范圍處理等。在這種情況下,您最好創建一個新的NSMutableAttributedString並從頭開始設置屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM