How to select a row programmatically in table View ? (Swift 4.0)

Viewed 3978

I have a tableViewController, my data source work well, but i can't select a row programmatically.

I have tried:

class DocumentTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)
     }
}

when I run, the tableView selects nothing. How can I solve that ?

2 Answers

Your line is very earlier try it in

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!) 
}

or this inside viewDidLoad

tableView.reloadData()
tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)

in swift 5:

tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableView.ScrollPosition(rawValue: 0)!)
Related