在Cocoa OS X的NSTableView中选择单元格时调用哪种方法?

问题描述 投票:7回答:5

我有一个NSTableView,我想获取单元格中存在的值。我只有一列,所以,我只需要行号

我可以使用此[tableView selectedRow]-,但是我要将其放在哪里,所以我希望将其放在一个在选择任何行时都会调用的方法。

-(void)tableViewSelectionDidChange:(NSNotification *)notification{

NSLog(@"%d",[tableViewController selectedRow]);

}

上述方法也不起作用,我收到错误消息-[NSScrollView selectedRow]:无法识别的选择器已发送到实例0x100438ef0]

我想要类似iPhone tableview中可用的方法-

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
}
xcode cocoa osx-snow-leopard nstableview
5个回答
27
投票

什么是tableViewController对象?仅NSTableView实例响应selectedRow。您可以从notification的对象属性中获取当前的表格视图(发送通知的视图):

Objective-C:

-(void)tableViewSelectionDidChange:(NSNotification *)notification{
    NSLog(@"%d",[[notification object] selectedRow]);
}

Swift:

func tableViewSelectionDidChange(notification: NSNotification) {
    let table = notification.object as! NSTableView
    print(table.selectedRow);
}

3
投票

我为Xcode 10 / swift 4.2支付2美分

  func tableViewSelectionDidChange(_ notification: Notification) {
        guard let table = notification.object as? NSTableView else {
            return
        }
        let row = table.selectedRow
        print(row)
    }

1
投票

Swift 3(摘自Eimantas的回答:]:>

func tableViewSelectionDidChange(_ notification: NSNotification) {
    let table = notification.object as! NSTableView
    print(table.selectedRow);
}

0
投票

您应该这样添加Observer通知


0
投票

[ override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didSelectRow(_:)), name: NSTableView.selectionDidChangeNotification, object: tableView) } @objc func didSelectRow(_ noti: Notification){ guard let table = noti.object as? NSTableView else { return } let row = table.selectedRow print(row) } deinit { NotificationCenter.default.removeObserver(self) }

© www.soinside.com 2019 - 2024. All rights reserved.