以编程方式更改标题在 IB 中设置为属性的 UIButton 的标题 [英] Programmatically change title of UIButton whose title was set in IB as attributed

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

问题描述

UIButton在使用前我已经改了标题:

I have changed titles of UIButtons before using:

- (void)setTitle:(NSString *)title forState:(UIControlState)state

但是 我遇到了一种情况,其中 UIButton 我正在使用的有一个多行标题,并且如果在 IB 中从普通"更改为属性",则只会将文本正确居中.以这种方式更改标题时,通常的 setTitle: forState: 方法不再更新按钮.

But I've run into a situation where the UIButton I'm using has a mult-line title and will only center the text properly if changed from "plain" to "attributed" in IB. When the title is changed in this way, the usual setTitle: forState: method no longer updates the button.

如何更改 UIButton归属标题?

为了澄清,所以你不要以为我只是犯了一个愚蠢的错误,我使用调试器来查看 UIButton 的属性并记录

To clarify, so you don't assume I'm just making a stupid mistake, I've used the debugger to peek at the properties of the UIButton and logging the output of

- (NSString *)titleForState:(UIControlState)state

使用后

- (void)setTitle:(NSString *)title forState:(UIControlState)state

设置它返回刚刚设置的值.问题是,只要在 IB 中将标题设置为 attributed,它就不会改变按钮的外观.只需将其更改为 plain,我的代码就可以正常工作.但这不是上面链接中描述的解决方案.

to set it returns the value just set. Problem is it doesn't change the appearance of the button as long as the title is set to attributed in IB. My code works fine by simply changing this to plain. But this is not a solution as described in the link above.

推荐答案

属性标题通过

- (NSAttributedString *)attributedTitleForState:(UIControlState)state

并通过设置

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state

格式化 NSAttributedString 对象有点复杂,但将其设置为 nil 会清除标题,而这正是我所需要的.

Formatting the NSAttributedString object is a bit complicated, but setting it to nil will clear the title and that's what I needed.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆