美文网首页
IBDesignable + IBInspectable 实时更

IBDesignable + IBInspectable 实时更

作者: 这个汤圆没有馅 | 来源:发表于2018-09-20 16:16 被阅读0次

前缀IB,平时我们见到最多的就是可视化编程中的IBAction 和 IBOutlet 。顾名思义,IBDesignable 和 IBInspectable 也是在可视化编程中使用。

用IBInspectable声明的属性,可在Xcode面板里的Runtime Attributes里直接配置。用IBDesignable表明的控件,则可以直接在storyboard/xib中看到修改上述属性产生的变化,不需要Run整个app。

1. 创建一个View,声明属性,一定要写set方法,不然不起作用。
  • Swift版本
@IBDesignable 
class TYView: UIView {
    @IBInspectable var cornerRadius: CGFloat {
        get { return layer.cornerRadius }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    @IBInspectable var borderWidth: CGFloat {
        get { return layer.borderWidth }
        set { layer.borderWidth = newValue > 0 ? newValue : 0 }
    }
    @IBInspectable var borderColor: UIColor {
        get { return UIColor(cgColor: layer.borderColor!) }
        set { layer.borderColor = newValue.cgColor }
    }
    @IBInspectable var height: CGFloat {
        get { return bounds.size.height }
        set { bounds.size.height = newValue }
    }
}
  • OC版本
@interface TYView : UIView
@property (nonatomic, assign) IBInspectable CGFloat connerRadius;
@property (nonatomic, assign) IBInspectable CGFloat borderWidth;
@property (nonatomic, strong) IBInspectable UIColor *borderColor;
@property (nonatomic, assign) IBInspectable CGFloat height;

@end

IB_DESIGNABLE
@implementation TYView
- (void)setConnerRadius:(CGFloat)connerRadius {
    _connerRadius = connerRadius;
    self.layer.cornerRadius = _connerRadius;
    self.layer.masksToBounds = YES;
}
- (void)setBorderWidth:(CGFloat)borderWidth {
    _borderWidth = borderWidth;
    self.layer.borderWidth = _borderWidth;
}
- (void)setBorderColor:(UIColor *)borderColor {
    _borderColor = borderColor;
    self.layer.borderColor = _borderColor.CGColor;
}
- (void)setHeight:(CGFloat)height {
    _height = height;
    CGRect temp = self.frame;
    temp.size.height = _height;
    self.frame = temp;
}

@end
2. 在storyboard拖一个view,Class选为自定义的类,点击面板上Runtime Attributes,会发现在类中声明的属性。直接修改值,storyboard上的view会直接刷新UI。
当设置完属性值后,切换到Indentity Inspector,会出现如下图红框内的attributes
有一点值得注意的是,若声明的属性本身自带也就是可以用点语法点出来的,比如backgroundColor。
若自定义属性名与自带属性名相同,则需要 override强制重写set方法,Runtime Attributes也会出现该属性,但是马上就会出现一个错误,并且storyboard页面已无法正常显示。编译的时候是success的,然而运行时就会直接crash。
@IBInspectable override var backgroundColor: UIColor? {
        get { return self.backgroundColor }
        set { self.backgroundColor = newValue }
    }
若自定义属性名与自带属性名不相同,但是set方法赋予自带属性的值。则xcode面板上会出现两处设置背景色的地方,同时设置两个颜色最后运行出来的则以自定义属性的值为准。
@IBInspectable  var backColor: UIColor? {
        get { return self.backgroundColor }
        set { self.backgroundColor = newValue }
}
WechatIMG329.jpeg

最后,swift一般用的都是类型推断, 不会直接注明属性的类型,所以有时可能会不起作用。只要加上类型标识声明类型后, 就能够在xib或者sb正常使用了。

相关文章

网友评论

      本文标题:IBDesignable + IBInspectable 实时更

      本文链接:https://www.haomeiwen.com/subject/czownftx.html