Eddy G Eddy G - 6 months ago 12
Swift Question

How to pre-select a table row at runtime?

I want to pre-select a table row in a splitView master controller as the view loads, Just like Apple does with the General selection in the Settings App in an Ipad.

I found some places suggesting using

let indexPathForSelection:NSIndexPath = tableView.selectRowAtIndexPath(indexPath: self, animated: false, scrollPosition: UITableViewScrollPositionNone)

but the Xcode does not recognize the scrollPosition code:
as a valid identifier

This should be a simple task but it seems no one is addressing it using Swift.


You have some mistakes in your code.

Your first mistake is, that you can't use the selectRowAtIndexPath method the way you do it. First you have to set the NSIndexPath. Like that:

var index = NSIndexPath(forRow: yourRow, inSection: yourSection)

Also you can't use UITableViewScrollPositionNone in Swift like you could in Objective-c. You have to use:


But I would recommend you use Middle in your case:


So to get the result you wanted, you should have to do something like this:

var index = NSIndexPath(forRow: yourRow, inSection: yourSection)
tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)