2015-11-09 84 views
0

我有一個具有23列NSTableView的應用程序。 NSTableView的內容綁定到IB中的ArrayController.arrangedObjects。另外,表中包含的每個NSTextFieldCell都具有綁定到表單元格視圖objectValue.someKey的值。我的一列有一個可編輯的值,所以我實現了controlTextDidEndEditing委託方法。另一個表列包含錯誤文本,並且它綁定到objectValue.errorText。從controlTextDidEndEditing委託方法訪問NSArrayController的綁定數組

上面提到的ArrayController有一個內容數組綁定到一個NSMutableArray,它是我的ViewController的一個屬性。該數組包含「事件」對象的集合,這些對象在應用程序啓動時定義和驗證。

因此,controlTextDidFinishEditing:方法有一個通知參數,在這種情況下,它是從中調用的NSTextField。我想在此方法中執行的操作是訪問綁定到ArrayController的NSMutableArray中包含的底層「Event」對象,並將「Event」對象的錯誤文本屬性設置爲@「」。

我會想象這有一個非常簡單的答案,但我努力試圖正確地使用我的Google查詢來產生我正在尋找的答案。

+1

您可以從控件遍歷具有'objectValue'的父級的視圖層次結構。你的'NSTextField'有一個superview,它是包含'objectValue'屬性的'NSTableViewCell'。您可以從'aNotification'對象的'userInfo'字典中獲得編輯的字段,找到哪個superview是'NSTableViewCell',並以這種方式獲取'objectValue'。不過,與使用委託方法相比,使用target-action來獲取視圖指針可能會更直接,而target-action將具有「sender」而不是「aNotification」。 – stevesliva

+0

另一件你可以做的就是重寫'someKey'設置器來設置'errorText'。或者將'errorText'作爲'someKey'的相關鍵路徑,並覆蓋'errorText' getter。這比遍歷視圖層次來得到相同的結果要乾淨得多。 – stevesliva

+0

@stevesliva我選擇使用你的第一個解決方案,因爲我想讓Event類儘可能通用,並且使它不是特定於實現的。這是我想出來的:' - (void)controlTextDidEndEditing:(NSNotification *)notification NSTextField * textField = [notification object]; NSView * superView = [textField superview]; Event * modifiedEvent =((NSTableCellView *)superView).objectValue; [modifiedEvent setTextColor:[NSColor blackColor]]; [modifiedEvent setErrorMessage:@「」]; return; }'非常感謝你! –

回答

0

這個答案來自實施@ stevesliva的第一個建議。

我定義了controlTextDidEndEditing:方法如下。

-(void)controlTextDidEndEditing:(NSNotification *)notification { 
    NSTextField *textField = [notification object]; 
    NSView* superView = [textField superview]; 
    Event* modifiedEvent = ((NSTableCellView*)superView).objectValue; 
    [modifiedEvent setTextColor:[NSColor blackColor]]; 
    [modifiedEvent setErrorMessage:@""]; 
    return; 
} 

這裏的關鍵是將superview的返回值作爲NSTableCellView *對象而不是通用的NSView *進行強制轉換。這樣做將允許您訪問objectValue屬性。

2

這個問題已經有了答案,但如果將來的讀者想知道綁定對象,他們可以檢查文本字段的綁定。

- (void)controlTextDidEndEditing:(NSNotification *)aNotification 
{ 
    NSTextField *textField = [aNotification object]; 
    NSDictionary* dictionary = [textField infoForBinding:NSValueBinding]; 
    NSTableCellView *tableCellView = [dictionary objectForKey:NSObservedObjectKey]; 
    NSString *keyPath = [dictionary objectForKey:NSObservedKeyPathKey]; 
    Event* modifiedEvent = tableCellView.objectValue; 
    [modifiedEvent setTextColor:[NSColor blackColor]]; 
    [modifiedEvent setErrorMessage:@""]; 
}