繁体   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