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

初始化

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值