在使用IBInspectable定義可視化屬性時(shí),對(duì)于枚舉類型,是沒法在xib上可視化的。代碼如下:
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
typedef enum : NSUInteger {
EMBorderViewTypeNone,
EMBorderViewTypeDash, ///< 虛線邊界線
EMBorderViewTypeSolid, ///< 實(shí)線邊界線
} EMBorderLineType;
typedef NS_OPTIONS(NSUInteger, EMBorderMode) {
EMBorderModeNone = 1 << 0, ///< 沒有邊界線
EMBorderModeLeft = 1 << 1, ///< 有左邊界線
EMBorderModeRight = 1 << 2, ///< 有右邊界線
EMBorderModeTop = 1 << 3, ///< 有上邊界線
EMBorderModeBottom = 1 << 4, ///< 有下邊界線
EMBorderModeAll = 1 << 5, ///< 有全部邊界線
};
IB_DESIGNABLE
@interface EMBorderView : NSView
@property (nonatomic,strong) IBInspectable NSColor *lineColor;
@property (nonatomic, assign) IBInspectable EMBorderLineType borderLineType; ///< 邊界線類型,對(duì)應(yīng)EMBorderLineType枚舉值
@property (nonatomic, assign) IBInspectable EMBorderMode borderMode; ///< 邊界線模式,對(duì)應(yīng)EMBorderMode枚舉值
@property (nonatomic, assign) IBInspectable CGFloat lineWidth; ///< 線寬
- (instancetype)initWithLineType:(EMBorderLineType)lineType mode:(EMBorderMode)mode;
@end
NS_ASSUME_NONNULL_END
這段代碼中,只有l(wèi)ineColor、lineWidth是可以可視化的:

clip_6.png
而2個(gè)枚舉屬性borderLineType和borderMode無法在屬性監(jiān)視器上顯示。
查了下資料,對(duì)于IBInspectable關(guān)鍵字支持的屬性類型,發(fā)現(xiàn)它僅支持以下幾種基礎(chǔ)數(shù)據(jù)類型的屬性:
Int
CGFloat
Double
String
Bool
CGPoint
CGSize
CGRect
UIColor
NSColor
UIImage
NSImage
我們知道枚舉本質(zhì)也就是NSIngeger或NSUInteger,所以為了讓這2個(gè)枚舉屬性可視化,我們可以將屬性這樣定義:
@property (nonatomic, assign) IBInspectable NSUInteger borderLineType; ///< 邊界線類型,對(duì)應(yīng)EMBorderLineType枚舉值
@property (nonatomic, assign) IBInspectable NSUInteger borderMode; ///< 邊界線模式,對(duì)應(yīng)EMBorderMode枚舉值
同時(shí)注意setter方法中也需要將其類型改為NSUInteger,如:
- (void)setBorderMode:(NSUInteger)borderMode {
if (_borderMode == borderMode) {
return;
}
_borderMode = borderMode;
[self refresh];
}
這樣我們就能在屬性監(jiān)視器上看到我們定義的屬性:

image.png
當(dāng)然,這個(gè)方法的缺點(diǎn)就是,在屬性監(jiān)視器中設(shè)置枚舉類型屬性時(shí),要自己對(duì)所需的枚舉值做運(yùn)算。這或許不是最好的方法,如果大家有什么更好的方法來優(yōu)雅的使用IBInspectable定義可視化屬性,歡迎大家討論不吝賜教~