UIButton初始化与样式
1.初始化UIButton
# ① 初始化方法一
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 200, 50)];
# ② 初始化方法二(推荐)
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame = CGRectMake(100, 100, 200, 50);
初始化后的的button
,文字颜色默认为白色,若背景也是白色,就看不见文字
2.设置button背景色

[btn setBackgroundColor:[UIColor redColor]];
3.设置button的title

[btn setTitle:@"这是一个按钮" forState:UIControlStateNormal];
4.设置titleLabel颜色

[btn1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
5.设置titleLabel背景颜色

btn1.titleLabel.backgroundColor = [UIColor whiteColor];
6.设置titleLabel位置

# 设置左对齐
btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
# 设置顶部对齐
btn1.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
7.设置边距

# 四个值分别对应 上,左,下,右(逆时针顺序)
btn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
8.设置字体大小

btn.titleLabel.font = [UIFont systemFontOfSize: 24.0];
9.设置圆角矩形边缘

btn.layer.cornerRadius = 5;
二、设置按钮背景颜色
1.设置按钮icon

[btn setImage:[UIImage imageNamed:@"icon_button"] forState:UIControlStateNormal];
按钮的icon
默认在titlelabel
左侧显示
2.设置按钮背景图片

背景图片会自动拉伸填充满整个按钮区,同时四周的圆角会消失
[btn setBackgroundImage:[UIImage imageNamed:@"icon_bg"] forState:UIControlStateNormal];
设置四周为圆角矩形

#两种方式都可以
btn.clipsToBounds = YES;
btn.layer.masksToBounds = YES;
区别:masksToBounds
是CALayer
的属性,而clipsToBounds
是UIView
的属性
clipsToBounds = YES
,则不会显示超过父View
的部分
masksToBounds = YES
,则不会显示超过父View layer
的部分
三、设置其他样式
1.设置边框

btn.layer.borderWidth = 1;
btn.layer.borderColor = [UIColor redColor].CGColor;
2.设置点击时特效
btn.showsTouchWhenHighlighted = YES;
3.设置按钮阴影

btn.layer.shadowColor = [UIColor blackColor].CGColor;
btn.layer.shadowOffset = CGSizeMake(15, 25);
btn.layer.shadowOpacity = 1;
btn.layer.shadowRadius = 1;
注意:设置阴影的时候不能同时设置clipsToBounds = YES
或者masksToBounds = YES
,否则阴影无法显示出来
4.添加响应事件
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
网友评论