设置UIButton的文字、字体、颜色等

来源:互联网 发布:破解linux root密码 编辑:程序博客网 时间:2024/05/16 06:01

初始化

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方法

0 0
原创粉丝点击