objective-c - 给予 NSTextField 焦点 -?

标签 objective-c cocoa osx-lion nstableview nstextfield

我目前有一个表格 View ,其中有单元格 View ,其中包含 NSTextFields。 目前,在行选择时,我向单元格 View 发送以下消息,希望授予单元格 View 中的 NSTextView 第一响应者状态:

- (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;
}

问题是,这只有一半的时间有效。我第一次尝试选择行时,第一响应者状态返回到 TableView 。第二次,它工作得很好,并且文本字段具有焦点。第三次,又断了。第四个——完美!由于某些奇怪的原因,该代码只能每隔一段时间才能工作......

有人知道为什么会这样吗?非常感谢任何有启发性的反馈。

最佳答案

当在 tableView 中从 textField 切换到 textField 时,事件会以意外的顺序调用(除非您考虑一下)。

这里的问题是调用委托(delegate)方法的顺序。

假设您要从 textField1 转到 textField2。

一旦 textField1 已经处于事件状态并且您单击 textField2,它们就会像这样被调用:

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

因为 textShouldBeginEditingtextDidEndEditing 之前调用(因为它需要确保它可以在放弃其旧的行之前选择该行一)您需要更新 textDidBeginEditing 中的 self.textField

关于objective-c - 给予 NSTextField 焦点 -?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10051056/

相关文章:

cocoa - Hillegass : Cocoa Prog 3rd Ed: Ch. 33 在 OpenGL : Where's the Matrix? 上

r - 在 Mac OSX 中从源安装 R 包时出错-找不到 "make"命令

objective-c - 什么是 QTCaptureScreenInput?

ios - 如何在 UICollectionView 中添加 Load more cell?

objective-c - dealloc 方法从 Xcode 4 中的 ViewController 实现文件模板中消失了吗?

ios - webViewDidFinishLoad 阻塞主线程

c# - Xamarin.Mac - 在窗口标题前显示图标/图像

objective-c - 我如何在 Objective-C/iOS 中表示无限数 ~0.99999 .....?

cocoa - 如何设置NSButton背景图片

numpy - 在 OS X 10.7.4 上为 Python 3.2.3 安装 NumPy