nwice13
nwice13

Reputation: 419

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

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 ?

Upvotes: 3

Views: 4604

Answers (2)

Fast
Fast

Reputation: 121

in swift 5:

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

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

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)!)

Upvotes: 5

Related Questions