How to select UITableView cell programmatically (Swift 2)

Viewed 6280

I have an UITableViewController and I need to select and scroll to one of the cells when the view loads. The reason I need the cell selected rather than just making it look selected (with an accessory or whatever) is that I want it to have a different background and no separators above/below (which is what happens when a table cell is selected), and I want the cell initially visible (if it's too far down).

I've read the two other answers and they don't work or I don't understand them. I'm not sure where I should put the self.tableView.selectRowAtIndexPath and self.scrollToRowAtIndexPath. I tried putting it in viewDidLoad() and it had no effect.

4 Answers

Swift 4:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let path = IndexPath(row: 0, section: 0)
    tableView.selectRow(at: path, animated: false, scrollPosition: .none)
}

Given solutions didn't work for me. So, here is the solution for swift 5

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    //Choose the row and section
    let indexPath = IndexPath(row: 0, section: 0)
    tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle)
    tableView.delegate?.tableView!(tableView, didSelectRowAt: indexPath)
}

Related