OS X開發:下拉菜單按鈕NSPopUpButton應用

OS X開發:下拉菜單按鈕NSPopUpButton應用

    NSPopUpButton是一個下拉按鈕,當用戶點擊時,其會彈出一個下拉選擇菜單。一個簡單的示例以下:數組

- (void)viewDidLoad {
    [super viewDidLoad];
    NSPopUpButton * popUpButton = [[NSPopUpButton alloc]initWithFrame:CGRectMake(100, 400, 200, 300)];
    //設置彈出菜單
    NSMenu * menu = [[NSMenu alloc]initWithTitle:@"menu"];
    [menu insertItemWithTitle:@"one" action:@selector(null) keyEquivalent:@"" atIndex:0];
    [menu addItemWithTitle:@"two" action:@selector(null) keyEquivalent:@""];
    popUpButton.menu = menu;
    //設置彈出菜單的位置
    popUpButton.preferredEdge = NSRectEdgeMaxX;
    [self.view addSubview:popUpButton];
}

效果以下圖所示:ui

NSPopUpButton繼承與NSButton,所以NSButton添加觸發事件的方式在NSPopUpButton中依然使用,NSPopUpButton類中屬性和方法解析以下:spa

//初始化方法 flag參數決定是下拉菜單模式仍是彈出菜單模式
- (instancetype)initWithFrame:(NSRect)buttonFrame pullsDown:(BOOL)flag;
//設置下拉菜單
@property (nullable, strong) NSMenu *menu;
//設置當交互事件發生時,是否禁用選項
@property BOOL autoenablesItems;
//風格設置是否爲下拉菜單
@property BOOL pullsDown;
//設置菜單彈出的優先位置
@property NSRectEdge preferredEdge;

//列表按鈕相關
//添加一個按鈕
- (void)addItemsWithTitles:(NSArray<NSString *> *)itemTitles;
//插入一個按鈕
- (void)insertItemWithTitle:(NSString *)title atIndex:(NSInteger)index;
//經過標題移除一個按鈕
- (void)removeItemWithTitle:(NSString *)title;
//經過索引移除按鈕
- (void)removeItemAtIndex:(NSInteger)index;
//移除全部按鈕
- (void)removeAllItems;
//全部列表選項按鈕數組
@property (readonly, copy) NSArray<NSMenuItem *> *itemArray;
//按鈕個數
@property (readonly) NSInteger numberOfItems;
//獲取按鈕索引的方法
- (NSInteger)indexOfItem:(NSMenuItem *)item;
- (NSInteger)indexOfItemWithTitle:(NSString *)title;
- (NSInteger)indexOfItemWithTag:(NSInteger)tag;
- (NSInteger)indexOfItemWithRepresentedObject:(nullable id)obj;
- (NSInteger)indexOfItemWithTarget:(nullable id)target andAction:(nullable SEL)actionSelector;
//獲取按鈕的方法
- (nullable NSMenuItem *)itemAtIndex:(NSInteger)index;
- (nullable NSMenuItem *)itemWithTitle:(NSString *)title;
//獲取最後一個按鈕
@property (nullable, readonly, strong) NSMenuItem *lastItem;
//選擇某個按鈕的方法
- (void)selectItem:(nullable NSMenuItem *)item;
- (void)selectItemAtIndex:(NSInteger)index;
- (void)selectItemWithTitle:(NSString *)title;
- (BOOL)selectItemWithTag:(NSInteger)tag;
- (void)setTitle:(NSString *)string;
//獲取選中的按鈕
@property (nullable, readonly, strong) NSMenuItem *selectedItem;
//獲取已經選中的按鈕索引
@property (readonly) NSInteger indexOfSelectedItem;
//獲取已經選中的按鈕tag
@property (readonly) NSInteger selectedTag;
//將選中的標題顯示進行同步
- (void)synchronizeTitleAndSelectedItem;

//獲取某個索引按鈕的標題
- (NSString *)itemTitleAtIndex:(NSInteger)index;
//獲取按鈕標題數組
@property (readonly, copy) NSArray<NSString *> *itemTitles;
//獲取選中的按鈕標題
@property (nullable, readonly, copy) NSString *titleOfSelectedItem;
//當下拉菜單彈出時發送的通知
APPKIT_EXTERN NSNotificationName NSPopUpButtonWillPopUpNotification;
相關文章
相關標籤/搜索