iOS中创建自定义的圆角按钮

iOS中很多时候都需要用到指定风格的圆角按钮,尽管UIButton提供了一个方式创建圆角按钮:

+ (id)buttonWithType:(UIButtonType)buttonType;//指定buttonType为UIButtonTypeRoundedRect

但是这样创建出来的按钮仅仅能支持默认的白底蓝字的风格,不可再进行更改。比如更改了backgroundColor,背景颜色区域仍然覆盖了整个矩形区域。

 

怎么做呢,通过摸索,以下方法能达到要求:

复制代码
UIButton *btn = [[UIButton alloc]initWithFrame:btnFrame];

// 设置圆角半径
btn.layer.masksToBounds = YES;
btn.layer.cornerRadius = 4;

//还可设置边框宽度和颜色
btn.layer.borderWidth = 1;
btn.layer.borderColor = [UIColor darkGrayColor].CGColor;
复制代码

 

这样得到的btn就可按自己需要的风格进行定义了,设置backgroundColor或backgroundImage都只是填充其圆角区域。

posted @ 2014-05-07 11:51  如来藏  阅读(351)  评论(0编辑  收藏  举报