2012-12-27 40 views
1

我有一個文本字段,我把它綁定到一個NSString實例變量。更新特性,而無需按Enter鍵

當我在文本字段中鍵入,它不更新變量。它會一直等到我按下Enter鍵。我不想每次都進入Enter。

我需要什麼,以便立即進行綁定變化值改變?

回答

4

默認情況下,該值NSTextField的結合不持續更新。爲了解決這個問題,你需要,選擇相應的文本字段後,檢查「不斷更新值」框中綁定檢查值標題下:

NSTextField Value binding with Continuously Updates Value checked.


然而,最常見的,當用戶完成編輯並按下按鈕時(例如,「保存」或「確定」),您真正想要執行的操作是更新文本字段綁定到的屬性。爲此,您不需要如上所述持續更新屬性,只需要結束編輯。 Daniel Jalkut provides an extremely useful implementation of just such a method

@interface NSWindow (Editing) 

- (void)endEditing; 

@end 

@implementation NSWindow (Editing) 

- (void)endEditing 
{ 
    // Save the current first responder, respecting the fact 
    // that it might conceptually be the delegate of the 
    // field editor that is "first responder." 
    id oldFirstResponder = [oMainDocumentWindow firstResponder]; 
    if ((oldFirstResponder != nil) && 
     [oldFirstResponder isKindOfClass:[NSTextView class]] && 
     [(NSTextView*)oldFirstResponder isFieldEditor]) 
    { 
     // A field editor's delegate is the view we're editing 
     oldFirstResponder = [oldFirstResponder delegate]; 
     if ([oldFirstResponder isKindOfClass:[NSResponder class]] == NO) 
     { 
      // Eh ... we'd better back off if 
      // this thing isn't a responder at all 
      oldFirstResponder = nil; 
     } 
    } 

    // Gracefully end all editing in our window (from Erik Buck). 
    // This will cause the user's changes to be committed. 
    if([oMainDocumentWindow makeFirstResponder:oMainDocumentWindow]) 
    { 
     // All editing is now ended and delegate messages sent etc. 
    } 
    else 
    { 
     // For some reason the text object being edited will 
     // not resign first responder status so force an 
     /// end to editing anyway 
     [oMainDocumentWindow endEditingFor:nil]; 
    } 

    // If we had a first responder before, restore it 
    if (oldFirstResponder != nil) 
    { 
     [oMainDocumentWindow makeFirstResponder:oldFirstResponder]; 
    } 
} 

@end 

所以,舉例來說,如果你有一個「保存」按鈕,定位到您的視圖控制器的方法-save:,你會打電話

- (IBAction)save:(id)sender 
{ 
    [[[self view] window] endEditing]; 
    //at this point, all properties bound to text fields have the same 
    //value as the contents of the text fields. 

    //save stuff... 
} 
0

以前的答案是美麗的,我從中學到了欺騙Window/View/Document系統根據編程人員的意願對所有內容進行編輯。

但是,默認的響應者鏈行爲(包括保存第一響應者,直到用戶將焦點轉移到其他東西上)是Mac的「外觀和感覺」的基礎,我不會輕易混淆它(I我發誓在響應鏈操作確實非常強大的東西,所以我就不多說了,由於害怕)

另外 - 甚至還有一個更簡單的方法 - 不需要改變的結合。在界面構建器中,選擇文本字段,然後選擇「屬性檢查器」選項卡。你會看到以下內容: Interface-Builder Attribute-inspector tab

檢查紅圈「連續」將做的伎倆。這個選項是基本的,比綁定更老,它的主要用途是允許驗證器對象(一個全新的故事)驗證文本並隨着用戶輸入而實時更改文本。當文本字段調用驗證器調用時,它還會更新綁定值。