将焦点移动到NSTableView中新添加的记录

hek*_*ran 13 macos cocoa objective-c nstableview

我正在使用Core Data编写一个应用程序来控制一些NSTableViews.我有一个添加按钮,在NSTableView中创建一个新的记录.单击此按钮时,如何将焦点移动到新记录,以便我可以立即键入其名称?这与iTunes中的想法相同,在单击添加播放列表按钮后,键盘焦点会立即移动到新行,以便您键入播放列表的名称.

Ale*_*ski 18

好的,首先,如果你还没有,你需要为你的应用程序创建一个控制器类.在控制器类的界面中添加NSArrayController存储对象的插座,以及NSTableView显示对象的插座.

IBOutlet NSArrayController *arrayController;
IBOutlet NSTableView *tableView;
Run Code Online (Sandbox Code Playgroud)

将这些插座连接到IB NSArrayControllerNSTableViewIB.然后,您需要创建一个IBAction在按下"添加"按钮时调用的方法; 调用它addButtonPressed:或类似的东西,在你的控制器类接口中声明它:

- (IBAction)addButtonPressed:(id)sender;
Run Code Online (Sandbox Code Playgroud)

并使其成为IB中"添加"按钮的目标.

现在,您需要在控制器类的实现中实现此操作; 此代码假定您添加到阵列控制器的对象是NSStrings; 如果不是,则将new变量的类型替换为要添加的任何对象类型.

//Code is an adaptation of an excerpt from "Cocoa Programming for
//Mac OS X" by Aaron Hillegass
- (IBAction)addButtonPressed:(id)sender
{
//Try to end any editing that is taking place in the table view
NSWindow *w = [tableView window];
BOOL endEdit = [w makeFirstResponder:w];
if(!endEdit)
  return;

//Create a new object to add to your NSTableView; replace NSString with
//whatever type the objects in your array controller are
NSString *new = [arrayController newObject];

//Add the object to your array controller
[arrayController addObject:new];
[new release];

//Rearrange the objects if there is a sort on any of the columns
[arrayController rearrangeObjects];

//Retrieve an array of the objects in your array controller and calculate
//which row your new object is in
NSArray *array = [arrayController arrangedObjects];
NSUInteger row = [array indexOfObjectIdenticalTo:new];

//Begin editing of the cell containing the new object
[tableView editColumn:0 row:row withEvent:nil select:YES];
}
Run Code Online (Sandbox Code Playgroud)

单击"添加"按钮后将调用此按钮,并开始编辑新行第一列中的单元格.