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

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

- (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??atom

1.其实不是,正常使用UIButton的时候设置Title是要对应Button的ControlState,由于UIButton继承于UIControl,在设置值得时候须要对象状态,因此通常都会用spa

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

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

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

 

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

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

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个值就能够正常显示,ip

不管你采用何种方式生产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不会遇到那么多麻烦。。。

相关文章
相关标签/搜索