IB_DESIGNABLE 和 IBInspectable 的用法
先贴出代码:
CircleView.h
#import <Cocoa/Cocoa.h>
IB_DESIGNABLE
@interface CircleView : NSView
@property (nonatomic, assign) IBInspectable CGFloat lineWidth;
@property (nonatomic, assign) IBInspectable CGFloat radius;
@property (nonatomic, strong) IBInspectable NSColor *color;
@property (nonatomic, assign) IBInspectable BOOL fill;
@end
CircleView.m
#import "CircleView.h"
@implementation CircleView
- (void)drawRect:(NSRect)dirtyRect {
// 圆心
CGFloat centerX = (self.bounds.size.width - self.bounds.origin.x) / 2;
CGFloat centerY = (self.bounds.size.height - self.bounds.origin.y) / 2;
NSBezierPath *path = [[NSBezierPath alloc] init];
// 添加一个圆形
[path appendBezierPathWithArcWithCenter:CGPointMake(centerX, centerY) radius:_radius startAngle:0 endAngle:360 clockwise:NO];
[path fill];
// 设置线条宽度
path.lineWidth = _lineWidth;
// 设置线条颜色
[_color setStroke];
//绘制线条
[path stroke];
if (_fill) {
// 如果是实心圆,设置填充颜色
[_color setFill];
// 填充圆形
[path fill];
}
}
@end
- IB_DESIGNABLE 修饰可使view在XIB中预览。
-
IBInspectable 属性修饰可在xib中设置属性值。
swift中@IBInspectable和@IBDesignable的使用
// 给uivew写一个扩展,定义三个属性
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
self.layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor(cgColor: self.layer.borderColor!)
}
set {
self.layer.borderColor = newValue.cgColor
}
}
}
// 自定义view,用@IBDesignable修饰
@IBDesignable class MyView: UIView {
}