在 xib 中可以通过user defined runtime attributes
来设置边框的相关属性,如图
so,我们可以利用
分类
和 iOS 的IBInspectable
关键字在 xib 添加自定义的属性。原理如下:
给 UIView 扩展一个分类,用IBInspectable修饰符来定义cornerRadius、borderWidth和borderColor属性,即可在 xib 上看见新增的三个属性了。
WX20181213-122949@2x.png
代码如下,源文件请点击:https://github.com/isWinner/LayerXibDemo
Object-C
@interface UIView (BorderCircle)
/* 圆角半径 */
@property(nonatomic, assign) IBInspectable CGFloat cornerRadius;
/* 边框宽度 */
@property(nonatomic, assign) IBInspectable CGFloat borderWidth;
/* 边框颜色 */
@property(nonatomic, weak) IBInspectable UIColor *borderColor;
@end
@implementation UIView (BorderCircle)
#pragma mark - -- borderColor
-(void)setBorderColor:(UIColor *)borderColor
{
self.layer.borderColor = borderColor.CGColor;
}
-(UIColor *)borderColor
{
return [UIColor colorWithCGColor:self.layer.borderColor];
}
#pragma mark - -- borderWidth
-(void)setBorderWidth:(CGFloat)borderWidth
{
self.layer.borderWidth = borderWidth;
}
-(CGFloat)borderWidth
{
return self.layer.borderWidth;
}
#pragma mark - -- cornerRadius
-(void)setCornerRadius:(CGFloat)cornerRadius
{
self.layer.masksToBounds = (cornerRadius>0);
self.layer.cornerRadius = cornerRadius;
}
-(CGFloat)cornerRadius
{
return self.layer.cornerRadius;
}
@end
Swift
extension UIView {
// 圆角
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
} set {
layer.masksToBounds = (newValue > 0)
layer.cornerRadius = newValue
}
}
// 边线宽度
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
} set {
layer.borderWidth = newValue
}
}
// 边线颜色
@IBInspectable var borderColor: UIColor {
get {
return UIColor(cgColor: layer.borderColor!)
} set {
layer.borderColor = newValue.cgColor
}
}
}
网友评论