iOS 中UIButton的 settitle 和 titlelabel的使用误区

转载自:http://www.cnblogs.com/Yukang1989/p/3716753.html

UIButton中设置Titl方法包括以下几种:

复制代码
- (void)setTitle:(NSString *)title forState:(UIControlState)state;        

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

@property(nonatomic,readonly,retain) NSString *currentTitle;             

@property(nonatomic,readonly,retain) UILabel     *titleLabel;
复制代码

 

在定义UIButton的时候,经常会使用titleLabel.text设置UIButton的值,但是Run出来确啥都没显示,不起作用啊!!!,这是怎么会事?难道是API的bug??

1.其实不是,正常使用UIButton的时候设置Title是要对应Button的ControlState,因为UIButton继承于UIControl,在设置值得时候需要对象状态,所以一般都会用

setTitle:(NSString *)title forState:(UIControlState)state 设置 Title;

2.setAttributedTitle是iOS6之后的方法,使用起来很简单,没特色说明。实例如下:

 [uibutton setAttributedTitle:[[NSAttributedString alloc]initWithString:@"3333333"] forState:UIControlStateNormal];

 

3.对应的currentTitle 也就是/normal/highlighted/selected/disabled状态下的title值,属性为readOnly;

4.至于titleLabel是设置的时候为啥不显示,比较神奇。查了官方文档以后才发现,真正的原因再于:(以下是我使用UIButton打印titleLabel对象的结果)

po uibutton.titleLabel
<UIButtonLabel: 0x7575800; frame = (0 0; 0 0); text = '11111111'; clipsToBounds = YES; hidden = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7572980>>

看到这里你明白了吗?

默认UIButton的titleLable是没设置frame的,而且hidden=YES;只要你设置这2个值就可以正常显示,

无论你采用何种方式生产UIButton:

复制代码
 UIButton *uibtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 30)]; 

否者  
UIButton
*uibtn = [UIButton buttonWithType:UIButtonTypeCustom];

[uibtn setFrame:CGRectMake(0, 100, 100, 30)];
复制代码

都一样;

 

总之,上面是我遇到过2次使用titleLabel不显示的总结,希望对以后有帮助。推荐使用第一种方式设置title不会遇到那么多麻烦。。。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值