有没有办法在Cocoa的绑定中更改(出于本地化的目的)空占位符?
绑定在Interface Builder中设置为弹出按钮。需要在IB中设置的绑定的双向性质,因此以编程方式执行它并不是真正吸引人的。
我知道处理nib文件本地化的标准方法是为每种语言创建一个,但由于这是语言版本之间整个nib文件的唯一区别,对于单个字符串来说似乎有点过分。
如果有办法修改在IB中创建的绑定,我正在考虑在文件的所有者的awakeFromNib
方法中执行它。
在绑定到的控制器对象(例如NSDocument类)中,覆盖-bind:toObject:withKeyPath:options:
。这需要成为该方法调用的目标 - 您在nib中选择Bind to:下的对象。
如果绑定到NSObjectController或NSArrayController,则需要一个子类。
该方法应该重写options
字典并调用super,用本地化的字符串替换NSNullPlaceholderBindingOption
的值。
我会省略nib中的null占位符和代码中的键值,尽管你当然可以获取该键的传入值并转换它。
另一个答案似乎不再起作用,所以我想出了一个稍微不同的解决方案,修改现有绑定以使用给定的空占位符字符串:
我在视图控制器中有这个方法:
- (void)rebind:(NSString *)binding of:(id)object withNullPlaceholder:(NSString *)nullPlaceholder {
// Possibly a bad idea, but Xcode doesn't localize the null placeholder so we have do it manually.
NSDictionary *bindingInfo = [object infoForBinding:binding];
id bindObject = bindingInfo[NSObservedObjectKey];
NSString *keyPath = bindingInfo[NSObservedKeyPathKey];
NSMutableDictionary *options = [bindingInfo[NSOptionsKey] mutableCopy];
options[NSNullPlaceholderBindingOption] = nullPlaceholder;
[object unbind:binding];
[object bind:binding toObject:bindObject withKeyPath:keyPath options:options];
}
我在awakeFromNib
中将其称为需要它的所有绑定并传入本地化字符串:
- (void)awakeFromNib {
// Hacky hack hack: Xcode is stupid and doesn't localize the null placeholders so we have to do it.
[self rebind:@"contentValues" of:self.fooPopup withNullPlaceholder:NSLocalizedString(@"No foos available", @"foo popup null placeholder")];
[self rebind:@"contentValues" of:self.barPopup withNullPlaceholder:NSLocalizedString(@"No bars available", @"bar popup null placeholder")];
}
然后,本地化的字符串通常作为Localizable.strings
文件的一部分进行本地化。
我能够在使用绑定的NSPopUpButton
中更改空占位符字符串(即“无值”)。
具体来说,我希望有一个弹出按钮菜单项,其标题不是“无值”,表示对象为nil
。当选择空占位符菜单项时,应将空NSString
或nil
保存在用户默认值中。
NSPopUpButton绑定:
NSArrayController.arrangedObjects
NSArrayController.arrangedObjects.exampleContentObject
(NSString
),这是菜单项表示的对象,是Selected Object
,NSArrayController.arrangedObjects.exampleContentValue
(NSString
),这是弹出按钮菜单项中显示的标题。NSSharedUserDefaultsController.values.ExampleUserDefaultsKey
,它与Content Objects
和Selected Object
(NSString
)的对象类型相同。此对象应与绑定中指定的NSUserDefault密钥的对象类型匹配。当选择弹出按钮中的项目时,它会将选定对象保存为用户默认值。要将空占位符字符串从“无值”更改为其他内容,请继承NSPopUpButton
并覆盖-[NSPopUpButton bind:toObject:withKeyPath:options:]
。
@interface CustomPopUpButton : NSPopUpButton
@end
@implementation CustomPopUpButton
- (void)bind:(NSString *)binding toObject:(id)observable withKeyPath:(NSString *)keyPath options:(NSDictionary<NSString *,id> *)options {
NSMutableDictionary *mutableOptions = options ? [options mutableCopy] : [NSMutableDictionary dictionaryWithCapacity:1];
mutableOptions[NSInsertsNullPlaceholderBindingOption] = @YES;
mutableOptions[NSNullPlaceholderBindingOption] = @"Custom Null Placeholder Text";
[super bind:binding toObject:observable withKeyPath:keyPath options:[mutableOptions copy]];
}
@end
最后,在Interface Builder中选择NSPopUpButton
,在Xcode Identity Inspector中的Custom Class下选择NSPopUpButton
子类中的类。