如何在表视图中以编程方式选择行?(斯威夫特4.0)

nwi*_*e13 3 uitableview swift

我有一个 tableViewController,我的数据源运行良好,但我无法以编程方式选择行。

我努力了:

class DocumentTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)
     }
}
Run Code Online (Sandbox Code Playgroud)

当我运行时,tableView什么也不选择。我该如何解决这个问题?

Sh_*_*han 5

你的线路很早尝试一下

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!) 
}
Run Code Online (Sandbox Code Playgroud)

或者里面这个viewDidLoad

tableView.reloadData()
tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)
Run Code Online (Sandbox Code Playgroud)