macOS - 自定义NSView在xib中显示和设置

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 {
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值