iOS-UIView设置圆角(懒人版)

要设置圆角,代码写的太麻烦了,要这样写:

view.layer.cornerRadius = cornerRadius;
view.layer.masksToBounds = YES;

在storyboard/xib直接设置,一般的方法是在User Defined Runtime Attributes里面加一条属性layer.cornerRadius,设置Value这样,如下图:

添加圆角操作.png

这样确实方便,但是,每次添加都要写一遍layer.cornerRadius,还是不够方便。

进阶版

于是,可以写一个UIView的Categorie来去掉这个步骤,完成后直接在storyboard/xib设置圆角数值即可。

先在.h文件添加属性:

@property (nonatomic, assign) IBInspectable CGFloat cornerRadx;
 ...

然后在.m文件添加set和get方法即可,这同样是用runtime实现(别忘了先 import ) :

- (void)awakeFromNib {
    [super awakeFromNib];

    self.layer.cornerRadius = self.cornerRadx;
}

static NSString *cornerRadxKey = @"cornerRadxKey";
- (void)setCornerRadx:(CGFloat)cornerRadx {
    objc_setAssociatedObject(self, &cornerRadxKey, @(cornerRadx), OBJC_ASSOCIATION_COPY);
}

- (CGFloat)cornerRadx {
    return [objc_getAssociatedObject(self, &cornerRadxKey) floatValue];
}

最后,在storyboar/xib中,任意继承自UIView的控件都会多一个Corner Radx属性可以设置了:

就这样.png

你可能感兴趣的:(iOS-UIView设置圆角(懒人版))