当前位置:   article > 正文

macOS - 自定义NSView在xib中显示和设置_maxos 加载 自定义view xib

maxos 加载 自定义view 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 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 {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/382888
推荐阅读
相关标签
  

闽ICP备14008679号