以编程方式更改UIButton的属性标题

16

我想以编程的方式更改一个具有属性标题的UIButton的标题。该按钮是在IB中创建的。我不想更改属性,只想更改标题/文本。

我尝试了下面的代码,但找不到一种更改NSAttributedString标题的方法。

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

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

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

谢谢!

3个回答

22

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

20

你部分地得到了答案。

 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

这真的取决于你的attributedString:

  • 'plain' attributedString: This means your attrString has only 1 set of attributes which apply to the entire length of the string. In this case, you can do the following:

    NSAttributedString *attrString = WHATEVER;
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL];
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER
                                                                        attributes:attributes];
    
  • your attributedString has different ranges of attributes:
    This can get really complicated depending on the structure of you attributedString, because you would have to do a lot of range handling, etc. In this case, you are better off creating a new NSMutableAttributedString and set the attributes from scratch.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接