TimSim
TimSim

Reputation: 4036

How to select UITableView cell programmatically (Swift 2)

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.

Upvotes: 3

Views: 8190

Answers (4)

Arslan Kaleem
Arslan Kaleem

Reputation: 1608

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

Upvotes: 1

Adam Bardon
Adam Bardon

Reputation: 3899

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

Upvotes: 3

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

Try to use viewDidAppear

func viewDidAppear(animated: Bool){
    super.viewDidAppear(animated)
    let path = NSIndexPath(forRow: 1, inSection: 0)
    tableView.selectRowAtIndexPath(myPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
}

Upvotes: 10

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

Use the selectRowAtIndexPath method of UITableView in your view controller's viewDidAppear method

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    // replace forRow: value with the index of the cell
    // replace inSection: value with the section the cell is in
    let indexPath = NSIndexPath(forRow: 2, inSection: 0)
    tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle)
}

Upvotes: 2

Related Questions