我的应用程序包含一个“播放/暂停”按钮,该按钮设置为在 Interface Builder 中键入“Toggle”。正如其名称所示,我使用它来播放或暂停我的资源。
此外,我正在听空格键以通过键盘快捷键启用相同的功能。因此,我在应用程序中使用来自 NSResponder
的 keyDown:
。这是在另一个 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/