NSButton控件用來建立功能按鈕,和UIButton相比,其樣式要豐富許多。NSButton繼承自NSControl,其使用setTarget與setAction來添加觸發方法,如下:
NSButton * btn = [[NSButton alloc]initWithFrame:CGRectMake(50, 300, 90, 25)];
[btn setTarget:self];
[btn setAction:@selector(click)];
[self.view addSubview:btn];
NSButton類中常用屬性和方法解析如下:
//設定按鈕标題
@property (copy) NSString *title;
//設定按鈕開啟狀态的标題
@property (copy) NSString *alternateTitle;
//設定按鈕圖檔
@property (nullable, strong) NSImage *image;
//設定按鈕開啟狀态圖檔
@property (nullable, strong) NSImage *alternateImage;
//設定按鈕圖檔位置
/*
typedef NS_ENUM(NSUInteger, NSCellImagePosition) {
NSNoImage = 0, //無圖檔
NSImageOnly = 1, //隻有圖檔
NSImageLeft = 2, //圖檔在左側
NSImageRight = 3, //圖檔在右側
NSImageBelow = 4, //圖檔在下側
NSImageAbove = 5, //圖檔在上側
NSImageOverlaps = 6, //圖檔重疊
NSImageLeading API_AVAILABLE(macosx(10.12)) = 7, //正方向
NSImageTrailing API_AVAILABLE(macosx(10.12)) = 8 //逆方向
};
*/
@property NSCellImagePosition imagePosition;
//設定圖檔縮放模式
typedef NS_ENUM(NSUInteger, NSImageScaling) {
NSImageScaleProportionallyDown = 0, // 下方縮放
NSImageScaleAxesIndependently, // 整體縮放
NSImageScaleNone, // 不縮放.
NSImageScaleProportionallyUpOrDown, // 上下縮放
NSScaleProportionally NS_ENUM_DEPRECATED_MAC(10_0, 10_10, "Use NSImageScaleProportionallyDown instead") = 0,
NSScaleToFit NS_ENUM_DEPRECATED_MAC(10_0, 10_10, "Use NSImageScaleAxesIndependently instead"),
NSScaleNone NS_ENUM_DEPRECATED_MAC(10_0, 10_10, "Use NSImageScaleNone instead")
@property NSImageScaling imageScaling NS_AVAILABLE_MAC(10_5);
//圖檔是否環繞标題
@property BOOL imageHugsTitle;
//設定按鈕狀态
enum {
NSMixedState = -1, //混合狀态
NSOffState = 0, //關閉狀态
NSOnState = 1, //開啟狀态
@property NSInteger state;
//設定是否顯示邊框
@property (getter=isBordered) BOOL bordered;
//設定按鈕是否透明
@property (getter=isTransparent) BOOL transparent;
//設定快捷鍵
@property (copy) NSString *keyEquivalent;
//設定富文本标題
@property (copy) NSAttributedString *attributedTitle;
@property (copy) NSAttributedString *attributedAlternateTitle;
//設定邊框風格
@property NSBezelStyle bezelStyle;
//設定是否當滑鼠移動到按鈕上時顯示邊框
@property BOOL showsBorderOnlyWhileMouseInside;
//設定按鈕聲音
@property (nullable, strong) NSSound *sound;
下面是一些便捷建立按鈕的方法:
//建立标準的按鈕 包括标題和圖檔
- (instancetype)buttonWithTitle:(NSString )title image:(NSImage )image target:(nullable id)target action:(nullable SEL)action;
//建立文字按鈕
- (instancetype)buttonWithTitle:(NSString *)title target:(nullable id)target action:(nullable SEL)action;
//建立圖檔按鈕
- (instancetype)buttonWithImage:(NSImage *)image target:(nullable id)target action:(nullable SEL)action;
//建立複選框按鈕
- (instancetype)checkboxWithTitle:(NSString *)title target:(nullable id)target action:(nullable SEL)action;
//建立單選框按鈕
- (instancetype)radioButtonWithTitle:(NSString *)title target:(nullable id)target action:(nullable SEL)action;