Objective C class Interface Builder 中的类别

Objective C class category in Interface Builder

我在 Objective C 中创建了一个 class 类别:

#import <UIKit/UIKit.h>

@interface UIView (LayerProperties)

@property IBInspectable (nonatomic) CGFloat cornerRadius;
@property IBInspectable (nonatomic) CGFloat borderWidth;
@property IBInspectable (nonatomic, strong) UIColor *borderColour;

@end

如果我导入 header,这一切都很好并且有效。当我添加 UIView 时,如何让这个类别显示在 Interface Builder 中?

您需要子class 一个视图,您应该在其中导入该类别。然后使用该子classed 视图更改故事板视图,然后您类别中的所有属性都应该可用。

例如

#import "LayerProperties+UIView.h"
@interface MyCustomView : UIView
@end

现在在 IB 中,将您的视图 class 更改为 MyCustomView

试试这个。界面生成器中的 KVC。也许你需要子类

或者创建子类并使用IBInspectable / IBDesignable (http://nshipster.com/ibinspectable-ibdesignable/ )

我在说傻话。唯一的错误是我在 属性 定义中将 IBInspectable 宏放在了错误的位置:

@property IBInspectable (nonatomic) CGFloat cornerRadius;

应该是:

@property (nonatomic) IBInspectable CGFloat cornerRadius;

愚蠢的错误,可能会帮助其他人节省一些时间。现在所有属性都显示在所有视图(和视图子类)上: