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不會遇到那么多麻煩。。。