【问题标题】:How to deal with a Toggle NSButton?如何处理切换 NSButton?
【发布时间】:2011-08-29 16:14:07
【问题描述】:

我的应用程序包含一个播放/暂停按钮,该按钮设置为在 Interface Builder 中键入 Toggle。顾名思义,我使用它来播放我的资产或暂停它们。
此外,我正在听 SPACE 键以通过键盘快捷键启用相同的功能。因此,我在我的应用程序中使用来自NSResponderkeyDown:。这是在另一个子视图中完成的。此时按钮本身不可见。
我将当前的播放状态存储在单例中。

在考虑到其状态可能已被键盘快捷键更改的情况下,您将如何更新工具按钮的标题/替代标题?我可以使用绑定吗?

【问题讨论】:

  • 具体来说,您是如何“听空格键”的?
  • @Peter Hosey 我添加了一些信息。感谢您的语法编辑。
  • 你在哪里实现keyDown:? NSButton 可让您在 Interface Builder 中直接在其上设置键盘快捷键。

标签: cocoa togglebutton nsbutton


【解决方案1】:

我设法实现了按钮标题的持续更新,如下所示。我为状态添加了一个编程绑定(在示例中为buttonTitle)。请注意,IBAction toggleButtonTitle: 不会直接更改按钮标题!相反,updateButtonTitle 方法负责此任务。由于self.setButtonTitle 被调用,上述绑定会立即更新。
以下示例显示了我试图描述的内容。

//  BindThisAppDelegate.h
#import <Cocoa/Cocoa.h>

@interface BindThisAppDelegate : NSObject<NSApplicationDelegate> {
    NSWindow* m_window;
    NSButton* m_button;
    NSString* m_buttonTitle;
    NSUInteger m_hitCount;
}

@property (readwrite, assign) IBOutlet NSWindow* window;
@property (readwrite, assign) IBOutlet NSButton* button;
@property (readwrite, assign) NSString* buttonTitle;

- (IBAction)toggleButtonTitle:(id)sender;

@end

以及实现文件:

//  BindThisAppDelegate.m
#import "BindThisAppDelegate.h"

@interface BindThisAppDelegate()
- (void)updateButtonTitle;
@end


@implementation BindThisAppDelegate

- (id)init {
    self = [super init];
    if (self) {
        m_hitCount = 0;
        [self updateButtonTitle];
    }
    return self;
}

@synthesize window = m_window;
@synthesize button = m_button;
@synthesize buttonTitle = m_buttonTitle;

- (void)applicationDidFinishLaunching:(NSNotification*)notification {
    [self.button bind:@"title" toObject:self withKeyPath:@"buttonTitle" options:nil];
}

- (IBAction)toggleButtonTitle:(id)sender {
    m_hitCount++;
    [self updateButtonTitle];
}

- (void)updateButtonTitle {
    self.buttonTitle = (m_hitCount % 2 == 0) ? @"Even" : @"Uneven";
}

@end

如果您将状态存储在枚举或整数中,自定义 NSValueTransformer 将帮助您将状态转换为其按钮标题等效项。您可以将NSValueTransformer 添加到绑定选项中。

NSDictionary* options = [NSDictionary dictionaryWithObject:[[CustomValueTransformer alloc] init] forKey:NSValueTransformerBindingOption];
[self.button bind:@"title" toObject:self withKeyPath:@"buttonTitle" options:options];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多