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

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

问题描述

我在使用之前更改了 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中设置为归属,它就不会改变按钮的外观。只需将其更改为 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.

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

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