如何在表格视图中以编程方式选择一行?(Swift 4.0)

3

我有一个tableViewController,我的数据源正常工作,但我无法通过编程方式选择一行。

我尝试过:

class DocumentTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)
     }
}

当我运行时,tableView没有选择任何内容。我该如何解决?

在那个时候(viewDidLoad),你设置了tableView的数据源和代理吗?此时它是否有数据? - Scriptable
你设置了代理吗? - PaFi
1
在UITableViewController中不需要使用delegate和datasource。 - Shehata Gamal
这个回答解决了你的问题吗?如何在Swift中以编程方式选择UITableView中的行 - Sourabh Sharma
2个回答

5
你的这行代码非常早,尝试在以下位置使用它:
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!) 
}

viewDidLoad中添加以下内容:
tableView.reloadData()
tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableViewScrollPosition(rawValue: 0)!)

1
在 Swift 5 中:
tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: UITableView.ScrollPosition(rawValue: 0)!)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接