初始化
UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 20)];
[self.view addSubview:cancelButton];
這樣初始化的button,文字預設顔色是白色的,所有如果背景也是白色的話,是看不到文字的
設定文字、顔色
cancelButton.titleLabel.textColor = [UIColor greenColor];
cancelButton.titleLabel.text = @"取消";
使用上面的方式,設定的文字沒有效果,無法顯示出來,因為titleLabel屬性是readonly的,隻能讀值,不能設值。
類似的還有imageView、currentBackgroundImage等屬性。正确的方法是調用 set開頭的一些api,比如:
[cancelButton setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[cancelButton setTitle:@"取消" forState:UIControlStateNormal];
設定文字位置
設定文字位置,現設為居左,預設的是居中
cancelButton.titleLabel.textAlignment = UITextAlignmentLeft;
這是不行的,需要如下設定:
cancelButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
如果希望文字與邊框有邊距,則:
cancelButton.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 0);
設定背景色
直接設定backgroundColor屬性
cancelButton.backgroundColor = [UIColor yellowColor];
或者
[cancelButton setBackgroundColor:[UIColor yellowColor]];
它其實就是 backgroundColor屬性的getter方法