2015-03-18 37 views
0

我有一個OS X應用程序與兩個複選框(NSButton)。如果第一個(主)未選中,則禁用並取消選中第二個。我可以在發送操作前獲取一個複選框以在視覺上更改其狀態?

下面是該功能的代碼,

@IBAction func peopleCheckboxAction(sender: AnyObject) { 
    if(self.peopleCheckbox.state == NSOffState){ 
     self.peopleCommentsCheckbox.enabled = false 
     self.peopleCommentsCheckbox.state = NSOffState 

    }else{ 
    self.peopleCommentsCheckbox.enabled = true} 

} 

但這裏的東西:第一個複選框的狀態更改之前的代碼被執行,並創建一個兩步動作,感覺就像第一盒子沒有反應,或者用戶可能點擊了錯誤的按鈕,因爲第二個控件先改變了。這只是一個節拍,但我想解決它。

是否有一種簡單的方法來扭轉這兩件事情的執行方式,或者確保它們幾乎同時發生?

回答

0

你可以看到你使用綁定會帶來什麼樣的效果 - 這意味着完全消除了動作方法。

您通常會將其設置在Interface Builder(IB)中,但複製並粘貼以下代碼將很快讓您看到此方法是否足夠滿足您的需求。如果是的話,你可能應該努力將其全部置於IB中,只留下代碼中的peopleState屬性。

#import "AppDelegate.h" 

@interface AppDelegate() 

@property (weak) IBOutlet NSButton *peopleCheckBox; 
@property (weak) IBOutlet NSButton *commentCheckBox; 

@property NSNumber *peopleState; 

@property (weak) IBOutlet NSWindow *window; 

@end 

@implementation AppDelegate 


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 

    // Each time you click on the peopleState checkbox, 
    // the value of the property <peopleState> will change. 
    [self.peopleCheckBox bind:@"value" 
        toObject:self 
        withKeyPath:@"peopleState" 
         options:nil]; 

    // Each time the value of the property <peopleState> changes, 
    // the 'enabled' status of the commentCheckBox is updated 
    // peopleState == NSOffState -> commentCheckBox disabled. 
    [self.commentCheckBox bind:@"enabled" 
         toObject:self 
        withKeyPath:@"peopleState" 
         options:nil]; 
} 



@end 
+0

謝謝,我認爲這可能工作,但這裏有兩個問題。首先,似乎存在同樣的時間問題。其次,我實際上仍然需要關閉複選框以及禁用它。如果我只是將啓用的屬性綁定到它,那麼它可以被禁用,但commentCheckbox.state仍然是NSOnState。 – 2015-03-19 02:08:06

1

嘗試這種情況: [self.peopleCheckBox sendActionOn:NSLeftMouseDownMask]; (默認行爲是動作發送在鼠標上。)

相關問題