2012-04-07 69 views
2

我目前有一個tableview,其中包含NSTextFields的單元格視圖。 目前,關於行選擇,我要送電池查看下面的消息在小區鑑於第一響應者狀態授予NSTextView的希望:給予NSTextField焦點 - ?

- (void)notifyOfSelectionInWindow:(NSWindow *)window { 
    [[self textField] setEditable:YES]; 
    [[self textField] setSelectable:YES]; 
    // make textField (textView) first responder 
    [[self textField] selectText:nil]; 
    [[[self textField] currentEditor] setSelectedRange:NSMakeRange([[[self textField] stringValue] length], 0)];  
} 

因爲我不想NSTextFields可編輯當沒有選擇,他們都在排,我也爲此在我的自定義的NSTextField子類:

- (void)textDidEndEditing:(NSNotification *)notification { 
    [self setEditable:NO]; 
    [self setSelectable:NO]; 
    [super textDidEndEditing:notification]; 
} 

選擇更新代碼:(請注意,我也改變此行高度)

- (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(NSInteger)row { 
    // get the table veiw to animate/recalculate height of row 
    NSMutableIndexSet *changedRows = [NSMutableIndexSet indexSet]; 
    [changedRows addIndex:row]; 
    [changedRows addIndex:[tableView selectedRow]]; 
    [tableView noteHeightOfRowsWithIndexesChanged:changedRows]; 
    [rowView notifyOfSelectionInWindow:[self window]]; 
    //^this in turn calls a method of the same name of the corresponding cell view 
    return YES; 
} 

問題是,這個作品只有一半的時間。我第一次嘗試選擇一行時,第一個響應者狀態返回到表視圖。第二次,它完美地工作,並且文本字段有焦點。第三次,它再次破裂。第四 - 這是完美的!由於一些奇怪的原因,該代碼只能在其他時間...

任何人都有任何想法,爲什麼這是這樣嗎?任何啓發性的反饋非常感謝。

回答

2

在tableView中從textField切換到textField時,會以意外的順序調用事件(直到您考慮它爲止)。

這裏的問題是委託方法被調用的順序。

假設您將從textField1到textField2。

一旦textField1的已經是活動的,你點擊文字欄,他們獲得這樣調用:

textShouldBeginEditing (textField2) 
textShouldEndEditing (textField1) 
textDidEndEditing  (textField1) 
textDidBeginEditing  (textField2) 

因爲textShouldBeginEditing調用之前textDidEndEditing(因爲它需要確保它可以選擇前行它放棄了它的舊的),你需要更新你的self.textField而不是textDidBeginEditing