I have an application that is viewbased and I am adding a tableview as a subview to the main view. I have taken UITableViewDelegate
to respond the table methods.
Here is my solution for swift 3.0:
var selectedDefaultIndexPath = false
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if dataSource.isEmpty == false, selectedDefaultIndexPath == false {
let indexPath = IndexPath(row: 0, section: 0)
// if have not this, cell.backgroundView will nil.
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
// trigger delegate to do something.
_ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
selectedDefaultIndexPath = true
}
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
cell?.selectedBackgroundView?.backgroundColor = UIColor(hexString: "#F0F0F0")
return indexPath
}