如何以编程方式选择UITableView单元格(Swift 2)

我有一个UITableViewController ,我需要在视图加载时选择并滚动到其中一个单元格。 我需要选择单元格而不是仅仅选择单元格(带附件或其他)的原因是我希望它具有不同的背景并且上方/下方没有分隔符(这是选择表格单元格时会发生的情况),我希望细胞最初可见(如果它太远了)。

我已经阅读了另外两个答案,但是它们不起作用或者我不理解它们。 我不确定应该在哪里放置self.tableView.selectRowAtIndexPathself.scrollToRowAtIndexPath 。 我尝试将它放在viewDidLoad() ,它没有任何效果。

尝试使用viewDidAppear

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

在视图控制器的viewDidAppear方法中使用UITableView的selectRowAtIndexPath方法

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

斯威夫特4:

 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let path = IndexPath(row: 0, section: 0) tableView.selectRow(at: path, animated: false, scrollPosition: .none) }