我设法实现了按钮标题的持续更新,如下所示。我为状态添加了一个编程绑定(在示例中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];