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

Jef*_*art 20 interface-builder uibutton ios

UIButton在使用之前更改了s的标题:

- (void)setTitle:(NSString *)title forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

我遇到的情况UIButton我使用的是多行标题,如果在IB中从"普通"变为"归属",则只能正确居中.以这种方式更改标题时,通常的setTitle: forState:方法不再更新按钮.

如何更改属性的标题UIButton

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

- (NSString *)titleForState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

使用后

- (void)setTitle:(NSString *)title forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*art 58

归属标题是通过

- (NSAttributedString *)attributedTitleForState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

并设置通过

- (void)setAttributedTitle:(NSAttributedString *)title forState:(UIControlState)state
Run Code Online (Sandbox Code Playgroud)

格式化NSAttributedString对象有点复杂,但设置它将nil清除标题,这就是我需要的.


Chr*_*ien 9

您是否在视图控制器类中将按钮指定为IBOutlet,并且它是否正确连接为Interface Builder中的插座(从新引用插座拖动到文件所有者并选择您的UIButton对象)?当我看到这些症状时,这通常是我遇到的问题.首先说明 - @property(non atomic,strong)IBOutlet UIButton *mybutton;

然后

[myButton setTitle: @"myTitle" forState: UIControlStateNormal];