Ios 以编程方式更改UIButton的属性化标题
我想以编程方式更改具有属性标题的Ios 以编程方式更改UIButton的属性化标题,ios,uibutton,Ios,Uibutton,我想以编程方式更改具有属性标题的ui按钮的标题。 按钮是在IB中创建的。我不想更改属性,只想更改标题/文本 我尝试了下面的代码,但找不到更改NSAttributedString标题的方法 NSAttributedString *attributedString = [self.deleteButton attributedTitleForState:UIControlStateNormal]; // How can I change title of attributedString with
ui按钮的标题。
按钮是在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];
谢谢大家! 你有一部分答案
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[_ deleteButton attributedTitleForState:UIControlStateNormal]];
[attributedString replaceCharactersInRange:NSMakeRange(0, attributedString.length) withString:@"Your new string"];
[_ deleteButton setAttributedTitle:attributedString forState:UIControlStateNormal];
不必创建NSAttributedString
createNSMutableAttributedString
,您可以这样设置字符串。这实际上取决于您的attributedString:
- “普通”属性字符串:
这意味着您的attrString只有一组适用于整个字符串长度的属性。在这种情况下,您可以执行以下操作:
NSAttributedString *attrString = WHATEVER;
NSDictionary *attributes = [attrString attributesAtIndex:0 effectiveRange:NULL];
NSAttributedString *newAttrString = [[NSAttributedString alloc] initWithString:WHATEVER
attributes:attributes];
- attributedString具有不同的属性范围:
这可能会变得非常复杂,具体取决于attributedString的结构,因为您需要进行大量的范围处理等。在这种情况下,最好创建一个新的NSMutableAttributedString
并从头开始设置属性
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)
}
可以担保,仍然在Swift 5中工作。