如何在iPad的详细视图中选择默认项目?(在分割视图控制器中)

7

我正在使用分栏视图控制器。对于iPad,当应用程序启动时,我想在主视图控制器中选择第一项。那么我该如何在Swift中实现呢?谢谢!

3个回答

10

我解决了这个问题。我写这篇文章是为了帮助未来的其他人。

func viewDidLoad() {
        //..
        let initialIndexPath = NSIndexPath(forRow: 0, inSection: 0)
        self.tableView.selectRowAtIndexPath(initialIndexPath, animated: true, scrollPosition:UITableViewScrollPosition.None)

        if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
            self.performSegueWithIdentifier("ShowDetail", sender: initialIndexPath)
        }
}

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ShowDetail" {
            if sender!.isKindOfClass(UITableViewCell) {
                if let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell) {

                    // Get row from selected row in tableview

                }
            } else if sender!.isKindOfClass(NSIndexPath) {
                let tableCell = self.tableView.cellForRowAtIndexPath(sender as! NSIndexPath)
                let indexPath = self.tableView.indexPathForCell(tableCell!)

                // Get row from sender, which is an NSIndexPath
            }
        }
}

1

修复自动错误后,转换为Swift 5

let initialIndexPath = NSIndexPath(row: 0, section: 0)
self.tableView.selectRow(at: initialIndexPath as IndexPath, animated: true, scrollPosition:UITableView.ScrollPosition.none)
            
if UIDevice.current.userInterfaceIdiom == .pad {
    self.performSegue(withIdentifier: "ShowDetail", sender: initialIndexPath)
}

1

转换为Swift 3:

let initialIndexPath = IndexPath(row: 0, section: 0)
self.tableView.selectRow(at: initialIndexPath, animated: true, scrollPosition: UITableViewScrollPosition.none)
            
if UIDevice.current.userInterfaceIdiom == .pad {
    self.performSegue(withIdentifier: Constants.Segues.showDetail, sender: initialIndexPath)
}

这段代码应该放在哪里?我的 NewsViewController 子类没有 tableView 成员? - J.Doe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接