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

时间:2014-09-13 09:51:48

标签: ios uibutton

我想以编程方式更改具有属性标题的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 个答案:

答案 0 :(得分:18)

部分你有答案。

 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

答案 1 :(得分:11)

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

答案 2 :(得分:2)

这实际上取决于您的attributionString:

  • 'plain'adigofString: 这意味着您的attrString只有一组属性,适用于字符串的整个长度。在这种情况下,您可以执行以下操作:

    NSAttributedString *attrString = WHATEVER;
    NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL];
    NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER
                                                                        attributes:attributes];
    
  • 您的attributionString具有不同的属性范围:
    这可能会变得非常复杂,具体取决于您的attributesString的结构,因为您必须进行大量的范围处理等。在这种情况下,您最好创建一个新的NSMutableAttributedString并从头开始设置属性。