cocoa - 如何处理 Toggle NSButton?

标签 cocoa togglebutton nsbutton

我的应用程序包含一个“播放/暂停”按钮,该按钮设置为在 Interface Builder 中键入“Toggle”。正如其名称所示,我使用它来播放或暂停我的资源。
此外,我正在听空格键以通过键盘快捷键启用相同的功能。因此,我在应用程序中使用来自 NSResponderkeyDown: 。这是在另一个 subview 中完成的。按钮本身此时不可见。
我将当前的播放状态存储在单例中。

考虑到其状态可能已被键盘快捷键更改,您将如何更新toogle按钮的标题/替代标题?我可以使用绑定(bind)吗?

最佳答案

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

//  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 添加到绑定(bind)选项。

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

关于cocoa - 如何处理 Toggle NSButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7232772/

相关文章:

wpf - ItemsControl 中的 ToggleButtons 绑定(bind)到 ObservableCollection

swift - 当 isEnabled 为 false(禁用)时避免使 NSButton 透明/透明

objective-c - WebKit 框架中的shouldStartLoadWithRequest 等效项?

ios - dyld : Library not loaded: @rpath/Alamofire. framework/Versions/A/Alamofire 原因:找不到图像

objective-c - NSTableView 交替行颜色绘制不正确

flutter - 切换按钮,失败的断言行 188 pos 12 : 'isSelected ! = null 不是 true

javascript - JQuery:根据条款是否同意切换提交按钮

Cocoa通过写代码创建NSButton,样式如何设置?

cocoa - 在 Cocoa OSX 中以编程方式从窗口中删除按钮

iphone - 如何扩展我检查 2 张卡是否匹配到 3 张匹配的卡的方法?