设置Button的标题
在定义UIButton的时候,经常会使用titleLabel.text设置UIButton的值,但是Run出来没有任何显示,原因在于:
- 正常使用UIButton的时候设置Title是要对应Button的ControlState,因为UIButton继承于UIControl,在设置值得时候需要对象状态
- setAttributedTitle可以正确设置title,是设置UIButton里的Attribute,而不是组成UIButton里的titlelabel的text
[uibutton setAttributedTitle:[[NSAttributedString alloc]initWithString:@"titleText"] forState:UIControlStateNormal]
- 对应的currentTitle 也就是/normal/highlighted/selected/disabled状态下的title值,属性为readOnly
- 至于通过titleLabel的text不显示的原因是默认UIButton的titleLable是没设置frame的,而且hidden=YES;只要你设置这2个值就可以正常显示
UIButton *uibtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 100, 100, 30)];
或者UIButton *uibtn = [UIButton buttonWithType:UIButtonTypeCustom];[uibtn setFrame:CGRectMake(0, 100, 100, 30)];
1 | - (void)setTitle:(NSString *)title forState:(UIControlState)state; |