Set default selected cell in UITableViewController
try this:
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath)
// setup selectedBackgroundView
let backgroundSelectionView = UIView()
backgroundSelectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1)
cell.selectedBackgroundView = backgroundSelectionView
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
}
}
Sometimes your code are not always write inside the UIViewController, Ex: subclass a UITableView
You just need a flag and easy for further reuse
final class CustomTableView: UITableView {
private var rowDefaultSelected: Int = 0
//.....
}
And about UITableViewDelegate
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == rowDefaultSelected {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
rowDefaultSelected = -1
}
}
In Swift 4 this is the updated answer :)
class TableViewController: UITableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath)
// setup selectedBackgroundView
let backgroundSelectionView = UIView()
backgroundSelectionView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.1)
cell.selectedBackgroundView = backgroundSelectionView
return cell
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let indexPath = IndexPath(row: 0, section: 0)
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
Basically NSIndexPath has been replaced for IndexPath .