如何以编程方式为NSTabView添加绑定



我的应用程序包含一个带有两个制表符的NSTabView。此外,应用程序本身有一个枚举类型的playStateplayState保持在单例中。

typedef enum {
    kMyAppPlayStatePlaying,
    kMyAppPlayStatePaused
} MyAppPlayState;

playState在这里合成。

@property (readwrite) MyAppPlayState playState;

我想切换NSTabView每次playState的变化。因此,我准备了一个IBOutlet来添加一个类似于这个的绑定。

[self.playPauseTabView bind:@"selectedItemIdentifier" toObject:[MyAppState sharedState] withKeyPath:@"playState" options:nil];

我已经认识到identifier一定是NSString。这与我的枚举不匹配,它是一个int。我可以用NSValueTransformer来解决这个问题。
此外,selectedItemIdentifier不存在。NSTabView只提供selectedTabViewItem,然后允许访问identifierlabel。但是,我找不到一种方法来根据标识符切换项目本身。

在这种情况下,我发现自己在做两件事中的一件:

1)将self(或其他对象)注册为所讨论的属性的观察者,并在-observeValueForKeyPath:ofObject:change:context:中相应地设置所选选项卡。它可以像这样:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{ 
    if ( context == PlayStateChange )
    {
        if ( [[change objectForKey: NSKeyValueChangeKindKey] integerValue] == NSKeyValueChangeSetting )
        {
            NSNumber *oldValue = [change objectForKey: NSKeyValueChangeOldKey];
            NSNumber *newValue = [change objectForKey: NSKeyValueChangeNewKey];
            NSInteger oldInteger = [oldValue integerValue];
            NSInteger newInteger = [newValue integerValue];
            NSLog(@"Old play state: %ld, new play state: %ld", (long)oldInteger, (long)newInteger);
            // Do something useful with the integers here
        }
        return;
    }
}

2)声明一个只读NSString *属性,并声明它的值受你的playState属性的影响。像这样:

@property (readonly) NSString *playStateStr;
// Accessor
-(NSString *)playStateStr
{
    return playState == kMyAppPlayStatePlaying ? @"playing" : "paused";
}
+(NSSet *)keyPathsForValuesAffectingPlayStateStr
{
    return [NSSet setWithObject: @"playState"];
}

现在你有一个nsstring类型的属性,你可以绑定你的选项卡视图的选择。

我忘了在Interface Builder中连接NSTabView和它的IBOutlet
以下内容适合我。

NSDictionary* playStateOptions = [NSDictionary dictionaryWithObject:[[PlayStateValueTransformer alloc] init] forKey:NSValueTransformerBindingOption];
[self.playPauseTabView bind:@"selectedLabel" toObject:[MyAppState sharedState] withKeyPath:@"playState" options:playStateOptions];

NSValueTransformer中,我返回一个NSString,必须在每个选项卡的接口构建器中设置!

最新更新