将 NSSegmentedControl 绑定到布尔值?

发布于 2024-11-08 19:27:23 字数 431 浏览 0 评论 0原文

我对 Cocoa Bindings 还很陌生,即使在浏览了文档之后我也没有找到这个问题的答案。我想要做的是有一个只有两个段的分段控件。如果选择第一个段,则 NSUserDefaults 中的首选项应为 YES ,但如果选择第二段,则首选项应为 NO 。通过代码来完成此操作很简单:

-(IBAction)segmentSelectionChanged:(id)sender {
    NSInteger selectedSegment = [sender selectedSegment];
    [[NSUserDefaults standardUserDefaults] setBool:(selectedSegment==0)?YES:NO forKey:@"somepref"];
}

但我想通过绑定来完成此操作(所选索引看起来很有希望)。有办法做这样的事情吗?谢谢!

I'm still new to Cocoa Bindings and I haven't found an answer to this question even after looking through the docs. What I want to do is have a segmented control that only has two segments. If the first segment is selected, then a preference in NSUserDefaults should be YES , but if the second segment is selected, then the preference should be NO. This is trivial to do through code:

-(IBAction)segmentSelectionChanged:(id)sender {
    NSInteger selectedSegment = [sender selectedSegment];
    [[NSUserDefaults standardUserDefaults] setBool:(selectedSegment==0)?YES:NO forKey:@"somepref"];
}

but I'd like to do it through bindings (selected index looks promising). Any way to do something like this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戴着白色围巾的女孩 2024-11-15 19:27:23

我想你已经明白了——在 IB: 中绑定控件的 selectedIndex

Bind To: Shared User Defaults Controller
Controller Key: values
Key Path: WhateverYouWant

似乎工作得很好。

问题是您真的需要它是一个BOOL吗?无论如何,它只是 signed chartypedef 。请参阅 objc.h 第 43、49 和 50 行:

typedef signed char     BOOL;
// ...
#define YES             (BOOL)1
#define NO              (BOOL)0

您可以使用 integerForKey: 将值拉回并进行转换(可能更好,因为更明确):

(BOOL)[[NSUserDefaults sharedUserDefaults] integerForKey:@"WhateverYouWant"];

或者继续使用 boolForKey: 它应该可以正常工作。

I think you've got it already -- binding the control's selectedIndex in IB:

Bind To: Shared User Defaults Controller
Controller Key: values
Key Path: WhateverYouWant

seems to work just fine.

Is the problem that you really need it to be a BOOL? It's just a typedef for signed char anyways. See objc.h, lines 43, 49, and 50:

typedef signed char     BOOL;
// ...
#define YES             (BOOL)1
#define NO              (BOOL)0

You can pull the value back out using integerForKey: and cast it (possibly better because more explicit):

(BOOL)[[NSUserDefaults sharedUserDefaults] integerForKey:@"WhateverYouWant"];

or just continue using boolForKey: and it should work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文