本文介绍了以编程方式更改UIButton的属性标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to programmatically change the title of an UIButton which has an attributed title.The button is created in IB. I do not want to change the attributes just the title/text.

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

I've tried the code below but cannot find a way to change the title of the NSAttributedString.

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

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

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

谢谢!

推荐答案

部分地,您会得到答案.

Partially you have the answer.

 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 ,您只需设置这样的字符串即可.

Instead of creating NSAttributedString create NSMutableAttributedString then you can just set the string like this.

这篇关于以编程方式更改UIButton的属性标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:52