【发布时间】:2023-04-06 05:01:01
【问题描述】:
我正在尝试将可绑定属性添加到自定义 NSPopUpButton 子类。
我创建了一个“selectedKey”属性,用于存储与所选菜单项关联的 NSString。
在控件初始化中,我将 self 设置为按钮目标和按钮的操作 (valueChanged:),然后根据用户选择设置“selectedKey”:
@interface MyPopUpButton : NSPopUpButton {
NSMutableDictionary *_items;
NSString *_selectedKey;
}
@property(nonatomic, readwrite, copy) NSString* selectedKey;
- (void)addItemWithTitle:(NSString *)title andKey:(NSString *)key;
@end
@implementation MyPopUpButton
- (instancetype)initWithFrame:(NSRect)frameRect {
self = [super initWithFrame:frameRect];
if (self) {
_items = [NSMutableDictionary new];
[NSObject exposeBinding:@"selectedKey"];
[super setTarget:self];
[super setAction:@selector(valueChanged:)];
}
return self;
}
- (void)addItemWithTitle:(NSString *)title andKey:(NSString *)key {
[super addItemWithTitle:title];
[_items setValue:title forKey:key];
}
- (void)valueChanged:(id)sender {
for (NSString *aKey in [_items allKeys]) {
if ([[_items valueForKey:aKey] isEqualToString:[self titleOfSelectedItem]]) {
self.selectedKey = aKey;
}
}
}
- (void)setSelectedKey:(NSString *)selectedKey {
[self willChangeValueForKey:@"selectedKey"];
_selectedKey = selectedKey;
[self didChangeValueForKey:@"selectedKey"];
[self selectItemWithTitle:[_items valueForKey:selectedKey]];
}
@end
这似乎按预期工作:当用户更改 PopUpButton 选择时,“selectedKey”属性会更改。
很遗憾,尝试绑定此属性不起作用。
[selectButton bind:@"selectedKey" toObject:savingDictionary withKeyPath:key options:@{NSContinuouslyUpdatesValueBindingOption : @YES }]
更改选择时,绑定对象未进行相应更新。
我做错了什么?
【问题讨论】:
-
selectButton是什么对象? -
@PaulPatterson
selectButton是一个MyPopUpButton实例。它是在运行时(不是在 IB 中)创建并使用我自己的- (void)addItemWithTitle:(NSString *)title andKey:(NSString *)key方法填充的,以便填充它的菜单项和它的_items字典。 -
绕过您的问题:不需要自定义绑定。现有的绑定为您提供了很大的灵活性。您可以将内容、内容值和内容对象绑定到单独但相关的事物。 Content 是基础对象,Values 是这些对象中显示内容的关键路径,Objects 也是 Content 元素中作为弹出窗口的
objectValue返回的关键路径。内容对象还控制选定对象绑定映射到的内容。 -
@KenThomases 我经常为 NSPopUpButton 使用标准绑定(例如选定的值或选定的标签),但我目前正在处理一个相当复杂的项目,该项目涉及动态创建一组 NSPopUpButtons用于选择自定义 NSString ,该自定义 NSString 不是显示为它们的项目标题的内容。这就是我(可能是错误的)方法背后的原因。
-
将显示为项目标题的值与该项目表示的对象分离正是分离内容、内容值和内容对象绑定的原因。他们应该支持你所描述的。
标签: objective-c cocoa binding nsbutton nspopupbutton