1

私のアプリケーションには、Interface Builder でToggle型に設定された PLAY/PAUSE ボタンが含まれています。名前が示すように、アセットを再生または一時停止するために使用します。
さらに、キーボード ショートカットを介して同じ機能を有効にするために SPACE キーを聞いています。したがって、私は自分のアプリケーションでkeyDown:fromを使用しNSResponderます。これは別のサブビューで行われます。この時点では、ボタン自体は表示されません。
現在の再生状態を Singleton に保存します。

キーボード ショートカットによって状態が変更された可能性があることを考慮して、toogle ボタンのタイトル/代替タイトルをどのように更新しますか? バインディングを使用できますか?

4

1 に答える 1

2

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