我写的应用程序使用核心数据控制的几个NSTableViews.我有一个附加的按钮,使得一个新的记录在NSTableView.我怎么做的焦点移动到新记录,当这个按钮被点击以便我可以立即输入它的名字吗?这是同样的想法,在iTunes里之后立即点击播放列表中添加键的键盘重点移动到新的路线,所以你可以型的播放列表的姓名。

有帮助吗?

解决方案

好吧那么首先,如果你还没有已经有一个,你需要创建一个控制器类为您的应用。添加对你的对象被存储在一个NSArrayController出口,以及用于显示您的对象NSTableView的出口,在控制器类的接口。

IBOutlet NSArrayController *arrayController;
IBOutlet NSTableView *tableView;

这些插座连接到NSArrayControllerde和IB的NSTableView。然后,你需要创建一个被称为当你的“添加”按钮被按下的IBAction方法;称之为addButtonPressed:或类似的东西,在控制器类接口声明它:

- (IBAction)addButtonPressed:(id)sender;

和也使得其在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];
}

这将被称为当你点击“添加”按钮,并在新行的第一列的单元格将开始对其进行编辑。

其他提示

我相信,一个更加容易和更加适当的方式做到这一点是通过实施这种方式。

-(void)tableViewSelectionDidChange:(NSNotification *)notification {
    NSLog(@"%s",__PRETTY_FUNCTION__);
    NSTableView *tableView = [notification object];
    NSInteger selectedRowIndex = [tableView selectedRow];
    NSLog(@"%ld selected row", selectedRowIndex);

    [tableView editColumn:0 row:selectedRowIndex withEvent:nil select:YES];

I.e。

  1. 实施 tableViewSelectionDidChange:(NSNotification *)notification
  2. 取选择排的索引
  3. 呼叫 editColumn:(NSInteger)column row:(NSInteger)row withEvent:(NSEvent *)theEvent select:(BOOL)select 从那的排索引。

重要说明:这个解决方案也将触发的编辑时用户将简单地选择一个行。如果你只想要的编辑触发当添加一个新的对象,这不是给你的。

只要创建在控制器中的单独@IBAction和手动调用NSArrayController.add方法。之后,你可以选择行

@IBAction func addLink(_ sender: Any) {
    // Get the current row count from your data source
    let row = links.count

    arrayController.add(sender)

    DispatchQueue.main.async {
        self.tableView.editColumn(0, row: row, with: nil, select: true)
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top