Mac开发|NSComboBox

相关function

NSComboBoxDataSource中包含有如下的function

/* These two methods are required when not using bindings */
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)comboBox;   // 返回CombBox显示的数量
- (nullable id)comboBox:(NSComboBox *)comboBox objectValueForItemAtIndex:(NSInteger)index;    // 返回ComboBox显示的内容

- (NSUInteger)comboBox:(NSComboBox *)comboBox indexOfItemWithStringValue:(NSString *)string;    // 高亮已选的item
- (nullable NSString *)comboBox:(NSComboBox *)comboBox completedString:(NSString *)string; // 与`Autocompletes`相配合,实现类似自动查找的功能

NSComboBoxDelegate中包含的function

/* Notifications */
- (void)comboBoxWillPopUp:(NSNotification *)notification;
- (void)comboBoxWillDismiss:(NSNotification *)notification;
- (void)comboBoxSelectionDidChange:(NSNotification *)notification;
- (void)comboBoxSelectionIsChanging:(NSNotification *)notification;

需求:

首先会在UI上创建两个NSComboBox,然后通过获取配置的plist的值分别显示在UI上

  • 创建的用户界面如下图,并且将这两个NSComboBoxidentifier分别设置为value1value2,然后再勾选Uses Data Source:
用户界面
设置NSComboBox的identifier
勾选`Uses Data Source`
  • 拖拽NSComboBoxdataSourceView Controller进行相关联

  • 接下来就是代码部分,先要遵循协议NSComboBoxDataSource,具体实现如下代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.valueContent = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"value" ofType:@"plist"]];
}

#pragma mark -----------ComboBox function part-------------
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)comboBox {
    NSInteger num = 0;
    if ([comboBox.identifier isEqualToString:@"value1"]) {
        num = [[self.valueContent objectForKey:@"value1"] count];
    }else if ([comboBox.identifier isEqualToString:@"value2"]) {
        num = [[self.valueContent objectForKey:@"value2"] count];
    }

    return num;
}

- (nullable id)comboBox:(NSComboBox *)comboBox objectValueForItemAtIndex:(NSInteger)index {
    NSArray *comboBoxValue = [[NSArray alloc] init];
    if ([comboBox.identifier isEqualToString:@"value1"]) {
        comboBoxValue = [self.valueContent objectForKey:@"value1"];
    }else if ([comboBox.identifier isEqualToString:@"value2"]) {
        comboBoxValue = [self.valueContent objectForKey:@"value2"];
    }
    
    return [comboBoxValue objectAtIndex:index];
}
  • 最后效果图:
    效果图

其他

selectItemAtIndex:选择NSComboBox的默认值

- (NSUInteger)comboBox:(NSComboBox *)comboBox indexOfItemWithStringValue:(NSString *)string {
    NSInteger num = 0;
    num = self.valueOfUART.indexOfSelectedItem;
    
    return num;
}

你可能感兴趣的:(Mac开发|NSComboBox)