如何在不滚动的情况下选择表格视图中的单元格?

Swe*_*per 1 scroll uitableview ios swift

我正在使用表 VC 为我的应用程序构建设置屏幕。在 中viewDidLoad,我想通过选择单元格向用户显示他/她的当前设置。然后所选单元格的左侧会有一个复选标记。这是didSelectrowAtIndexPath方法:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    for row in 0..<tableView.numberOfRowsInSection(indexPath.section) {
        let cellToBeDeselected = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: indexPath.section))
        cellToBeDeselected?.accessoryType = .None
    }
    cell!.accessoryType = .Checkmark
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

这很好用。当我选择一行时,会出现一个复选标记。当我选择另一行时,上一个复选标记消失并出现一个新复选标记。

但是,我想在viewDidLoad中以编程方式选择行,以显示当前设置。

我找到了一个名为selectRowAtIndexPath. 我尝试使用它,但它需要一个UITableViewScrollPosition. 文档说:

给定行滚动到的表视图中的位置(顶部、中间、底部)。

似乎每当我想选择一行时,表格视图必须滚动到所选行所在的位置。但我只想选择它,并且选择它。

这该怎么做?

小智 5

正如文档中提到的,您可以指定UITableViewScrollPositionNone滚动位置,这将导致不滚动。

  • 你试了吗?对于该特定方法,它的行为有所不同。“传递 UITableViewScrollPositionNone 不会导致滚动,而不是为该常量描述的最小滚动。” (2认同)