Objective-C(Swift) IBDesignable/IBInspectable

iOS8新特性IBDesignable/IBInspectable,利用运行时机制,可以把属性映射到XIB上了,同时我们UI类的自定义属性也可以映射上去,可以直接在XIB或者Storyboard中设置UI类的属性。

Objective-C实例:
.h中代码如下

@interface ZWView : UIView

@property (nonatomic, assign)IBInspectable CGFloat cornerRadius;
@property (nonatomic, assign)IBInspectable CGFloat bwidth;
@property (nonatomic, assign)IBInspectable UIColor *bcolor;

@end

.m中代码:

#import "ZWView.h"
IB_DESIGNABLE

@implementation ZWView

- (void)setCornerRadius:(CGFloat)cornerRadius{
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius  = _cornerRadius;
    self.layer.masksToBounds = YES;
}

- (void)setBcolor:(UIColor *)bcolor{
    _bcolor = bcolor;
    self.layer.borderColor = _bcolor.CGColor;
}

- (void)setBwidth:(CGFloat)bwidth {
    _bwidth = bwidth;
    self.layer.borderWidth = _bwidth;
}

-(void)drawRect:(CGRect)rect{

    NSString *drawString = @"www.baidu.com";
    [drawString drawInRect:CGRectMake(20, 20, 180, 30) withFont:[UIFont systemFontOfSize:12.0]];

}

@end

在xib中拖入一个View,设置class为ZWView,设置完后便可以在xib中看到三个属性值
Objective-C(Swift) IBDesignable/IBInspectable_第1张图片

设置三个属性值后,效果如下:
Objective-C(Swift) IBDesignable/IBInspectable_第2张图片

Swift实例:

同样创建一个ZWView,代码如下:

import UIKit

@IBDesignable class zwView: UIView {

    @IBInspectable var cornerRadius:CGFloat = 0.0 {
        didSet{
           layer.cornerRadius = cornerRadius
           layer.masksToBounds = true
        }
    }

    @IBInspectable var borderColor:UIColor = UIColor(){
        didSet{
          layer.borderColor = borderColor.CGColor
        }
    }

    @IBInspectable var borderWith :CGFloat = 0.0{
        didSet{
           layer.borderWidth = borderWith
        }
    }
}

在xib中拖入View,设置class和属性值
Objective-C(Swift) IBDesignable/IBInspectable_第3张图片

效果如下:
Objective-C(Swift) IBDesignable/IBInspectable_第4张图片

你可能感兴趣的:(Objective-C,swift,IBInspecta,IBDesignab)