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

Mar*_*kus 13 uibutton ios

我想以编程方式更改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];
Run Code Online (Sandbox Code Playgroud)

谢谢!

Gop*_*ath 19

部分你有答案.

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

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

[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal]; 
Run Code Online (Sandbox Code Playgroud)

您可以像这样设置字符串,而不是创建NSAttributedString创建NSMutableAttributedString.


Dan*_*nny 12

斯威夫特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)
}
Run Code Online (Sandbox Code Playgroud)