自定义NSView在xib中显示和设置
2018-07-18 本文已影响19人
VictorZhangWang
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中设置属性值。