ボタンタイトルの継続的な更新を次のように実装することができました。状態のプログラムによるバインドを追加しました (例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];