本文主要介绍NSPopUpButton相关的功能及API。
NSPopUpButton
A display of a single item from a list of items, and provide an interface for selecting items from the list.
列表项中显示单个项目,并且提供从列表中选取项目的界面。
- 初始化
NSPopUpButton *popUpBtn = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(80, 80, 100, 30) pullsDown:NO];//pullsDown:YES表示创建pull-down menu,NO表示 pop-up menu
- 配置cell
//NSButtonCell *cell = [[NSPopUpButtonCell alloc] initTextCell:@"test3" pullsDown:YES];
//设置menu类型
[popUpBtn setPullsDown:NO];//pull-down menu or pop-up menu
[popUpBtn setAutoenablesItems:YES];//自动验证按钮是否可用
- 插入or删除item
[popUpBtn addItemWithTitle:@"test1"];//末尾追加item
[popUpBtn addItemWithTitle:@"test2"];
[popUpBtn addItemWithTitle:@"test3"];
[popUpBtn addItemsWithTitles:@[@"ok1", @"ok2"]];//通过array方式添加item
[popUpBtn insertItemWithTitle:@"insert" atIndex:2];
[popUpBtn removeItemWithTitle:@"insert"];
[popUpBtn removeItemAtIndex:0];
//[popUpBtn removeAllItems];
- 获取用户选中
NSMenuItem *selectedItem = [popUpBtn selectedItem];
NSString *title = [popUpBtn titleOfSelectedItem];
NSInteger index = [popUpBtn indexOfSelectedItem];
id obj = [popUpBtn objectValue];
NSInteger tag = [popUpBtn selectedTag];
- 设置当前选中
[popUpBtn selectItem:selectedItem];
[popUpBtn selectItemAtIndex:1];
[popUpBtn selectItemWithTag:0];
[popUpBtn selectItemWithTitle:@"ok2"];
[popUpBtn setObjectValue:[NSNumber numberWithInteger:0]];//具体索引的对象值
- 获取菜单项
NSMenu *menu = popUpBtn.menu;
NSInteger count = [popUpBtn numberOfItems];
NSArray *itemArr = [popUpBtn itemArray];
NSMenuItem *item = [popUpBtn itemAtIndex:0];
NSString *itemTitle = [popUpBtn itemTitleAtIndex:0];
NSArray *itemTitles = [popUpBtn itemTitles];
NSMenuItem *itemWithTitle = [popUpBtn itemWithTitle:@"ok2"];
NSMenuItem *lastItem = [popUpBtn lastItem];
- 获取菜单项的索引
NSInteger indexOfItem = [popUpBtn indexOfItem:selectedItem];
[popUpBtn indexOfItemWithTag:0];
[popUpBtn indexOfItemWithTitle:@"ok2"];
[popUpBtn indexOfItemWithRepresentedObject:[NSNumber numberWithInteger:0]];
[popUpBtn indexOfItemWithTarget:self andAction:@selector(test)];//特定target和action的索引
- 将单元格边缘设置为在受限情况下弹出
popUpBtn.preferredEdge = NSRectEdgeMaxX;
- 设置标题
[popUpBtn setTitle:@"PopUpButton"];//用户未选择时显示的文字
- 设置image
[popUpBtn setImage:[NSImage imageNamed:NSImageNameCaution]];//无影响
- 设置状态
[popUpBtn synchronizeTitleAndSelectedItem];//确保显示的项与所选项一致
- 通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popupBtnWillPop:) name:NSPopUpButtonWillPopUpNotification object:nil];