Cell Basedd的NSTableView中使用NSPopUpButtonCell,本人示例是动态设置的数据源。然后根据网络来的数据显示选中项。
这个东西坑的确很多,试了好多次才成功,而且没有官方文档。
//绑定数据源
-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
NSString *identifier = [tableColumn identifier];
NSDictionary *domainDic = [_records jk_objectWithIndex:row];
if([identifier isEqualToString:@"type"]){
//设置新数据
NSPopUpButtonCell *popCell = [tableColumn dataCellForRow:row];
[popCell removeAllItems];
for(int i=0;i<= [_types count];i++){
[popCell addItemWithTitle:[_types jk_objectWithIndex:i]?:@""];
}
//[popCell selectItemWithTitle:[domainDic jk_stringForKey:@"type"]];
//NSPopUpButtonCell 要返回index,带入默认选中项
return [NSNumber numberWithInteger:[popCell indexOfItemWithTitle:[domainDic jk_stringForKey:@"type"]]];
}
return nil;
}
//更改显示数据
- (void)tableView:(NSTableView *)tableView setObjectValue:(nullable id)object forTableColumn:(nullable NSTableColumn *)tableColumn row:(NSInteger)row{
NSMutableDictionary *domainDic = [[_records jk_objectWithIndex:row] mutableCopy];
NSString *identifier = [tableColumn identifier];
if([identifier isEqualToString:@"type"]){
//注意object为选中的index
NSPopUpButtonCell *popCell = [tableColumn dataCellForRow:row];
NSMenuItem *menuItem = [popCell itemAtIndex:[object integerValue]];
NSLog(@"%@", [menuItem title]); //DEBUG
[domainDic setObject:[menuItem title] forKey:@"type"];
}
[_records replaceObjectAtIndex:row withObject:domainDic];
}
转载请注明:天狐博客 » Cocoa开发之Cell Based NSTableView中使用NSPopUpButtonCell