Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select default item in detail view for iPad? (in Split View Controller)

I'm using a split-view controller. For iPad, when the app starts, I want to selected in the first item in master-view controller. So how can I do that in Swift? Thanks!

like image 998
etnclp Avatar asked Dec 03 '15 12:12

etnclp


2 Answers

I solved this problem. I am writing to help others in the future.

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
            }
        }
}
like image 83
etnclp Avatar answered Nov 13 '22 00:11

etnclp


Converted to 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)
}
like image 20
zorro2b Avatar answered Nov 13 '22 00:11

zorro2b