Programmatically change title of UIButton whose title was set in IB as attributed(以编程方式更改标题在 IB 中设置为属性的 UIButton 的标题)
问题描述
UIButton
在使用前我已经改了标题:
I have changed titles of UIButton
s 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 的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:以编程方式更改标题在 IB 中设置为属性的 UIButton 的标题


基础教程推荐
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- 固定小数的Android Money Input 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01