直接贴代码吧
- 1 、在UIView的扩展中的.h中添加(别说你的项目中没有对UIView进行扩展过)
@property (nonatomic)IBInspectable CGFloat cornerRadius;
@property (nonatomic)IBInspectable UIColor *borderColor;
@property (nonatomic)IBInspectable CGFloat borderWidth;
- 2、.m 中
static char layerCornerRadius = 0;
static UIColor *keyOfColor;
static float keyOfWidth;
-(void)setCornerRadius:(CGFloat)cornerRadius{
objc_setAssociatedObject(self, &layerCornerRadius,[NSString stringWithFormat:@"%f",cornerRadius],OBJC_ASSOCIATION_COPY_NONATOMIC);
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = cornerRadius > 0?true:false;
}
- (CGFloat)cornerRadius {
return [objc_getAssociatedObject(self, &layerCornerRadius)floatValue];
}
-(void)setBorderColor:(UIColor *)borderColor{
objc_setAssociatedObject(self, &keyOfColor, borderColor, OBJC_ASSOCIATION_COPY_NONATOMIC);
self.layer.borderColor = borderColor.CGColor;
}
-(UIColor *)borderColor{
// return [objc_getAssociatedObject(self, &keyOfColor)];
return [objc_getAssociatedObject(self, &keyOfColor)CGColor];
}
-(void)setBorderWidth:(CGFloat)borderWidth{
objc_setAssociatedObject(self, &keyOfWidth, [NSString stringWithFormat:@"%f",borderWidth], OBJC_ASSOCIATION_COPY_NONATOMIC);
self.layer.borderWidth = borderWidth;
}
-(CGFloat)borderWidth{
return [objc_getAssociatedObject(self, &keyOfWidth)floatValue];
}
然后编译以后在xib中,你就能够看到如下的选项了
这样以后就不需要在xib中通过keypath来进行设置view的边框了