以编程方式更改标题在 IB 中设置为属性的 UIButton 的标题

2023-07-07移动开发问题
1

本文介绍了以编程方式更改标题在 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 的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

[ios.cocos2d+box2d]如何禁用自动旋转?
[ios.cocos2d+box2d]how to disable auto-rotation?([ios.cocos2d+box2d]如何禁用自动旋转?)...
2024-08-12 移动开发问题
7

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9

如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?
How can I implement a virtual joystick for a cocos2d game outside the cocos2d environment?(如何在 cocos2d 环境之外实现 cocos2d 游戏的虚拟摇杆?)...
2024-08-12 移动开发问题
13