这里的诀窍是您需要其他地方来放置 NSComboBox 的值。 NSArrayController 可以很好地为 NSComboBox 提供库存值,但是您可以在 NSComboBox 中键入可能不在 NSArrayController 的 contentArray 中的任意值,因此您需要在其他地方放置值也就不足为奇了。我可以通过在 AppDelegate 上设置一个简单的值来快速模拟它,如下所示:
@interface SOAppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
// The NSArrayController you were talking about...
@property (assign) IBOutlet NSArrayController* popupValues;
// The other place to store data...
@property (retain) id comboBoxValue;
@end
然后在实现中:
@implementation SOAppDelegate
@synthesize window = _window;
@synthesize comboBoxValue = _comboBoxValue;
- (void)dealloc
{
[_comboBoxValue release];
_comboBoxValue = nil;
[super dealloc];
}
-(void)awakeFromNib
{
[super awakeFromNib];
NSMutableDictionary* item1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger: 1], @"id",
@"Item 1 Name", @"name",
@"Item 1 Description", @"description",
nil];
NSMutableDictionary* item2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger: 2], @"id",
@"Item 2 Name", @"name",
@"Item 2 Description", @"description",
nil];
NSMutableDictionary* item3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInteger:3], @"id",
@"Item 3 Name", @"name",
@"Item 3 Description", @"description",
nil];
NSMutableArray* array = [NSMutableArray arrayWithObjects: item1, item2, item3, nil];
self.popupValues.content = array;
}
@end
然后对于绑定,我是这样设置的:
NSComboBox:
- 内容 -> 数组 Controller.arrangedObjects
- 内容值 -> 数组 Controller.arrangedObjects.name
- Value -> App Delegate.comboBoxValue(如果您希望在输入 NSComboBox 时逐个字母更新 NSTextField,请检查
Continuously Updates Value)
NSTextField:
- Value -> App Delegate.comboBoxValue(如果您希望在输入 NSTextField 时逐字母更新 NSComboBox,请检查
Continuously Updates Value)
如果您希望将您键入的新值添加到数组中,我很遗憾地说,仅使用这两个控件和绑定并不容易做到这一点。这有点复杂。但是对于简单情况的技巧是,您需要一些位置来存储值 other,而不是用于向 NSComboBox 提供预加载值的 NSArrayController。