【问题标题】:swift3 scrollToRow even when there are empty cellsswift3 scrollToRow 即使有空单元格
【发布时间】:2016-10-05 12:42:18
【问题描述】:

我正在寻找一种方法来滚动到 UITableView 中选定的单元格,即使底部有一个空单元格。我的问题是,当表格视图底部没有单元格时,滚动事件不会滚动。

作为一种解决方法,我最终在底部创建了空单元格并删除了这些单元格,但我认为这不是一个好的解决方案。那么这个方法是怎么做到的呢?

我的代码如下所示:

func scrollToSelectedCell(indexPath: IndexPath) {
    self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath)

    if (cell as? DropDownCell) != nil {
        self.performSegue(withIdentifier: "showDropDownSelector", sender: cell)
    } else if (cell as? PickerCell) != nil {
        self.performSegue(withIdentifier: "showPickerSelector", sender: cell)
    } else if let tmp_cell = cell as? TextFieldCell {
        scrollToSelectedCell(indexPath: indexPath)
        tmp_cell.textField.becomeFirstResponder()
    }

}

【问题讨论】:

    标签: ios swift uitableview uiscrollview swift3


    【解决方案1】:

    您可以使用 UITableView 继承自 UIScrollView 的事实更优雅地执行此操作。这允许您使用组合设置 tableView 的内容插入,然后更改内容偏移量。

    使用 contentInset 属性在单元格下方的表格视图中添加边距:

    tableView.contentInset = UIEdgeInsetMake(top: 0, left: 0, bottom: A LARGE NUMBER, right: 0)
    

    然后使用 contentOffset 设置您希望内容的初始位置在滚动视图中的位置:

    tableView.contentOffset = CGPoint(x: 0, y: SOME OTHER LARGE NUMBER TO POSITION CENTRALLY IN THE MARGIN)
    

    您可以通过以下方式获取更多信息:https://developer.apple.com/reference/uikit/uiscrollview

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2018-01-14
      • 2021-07-14
      • 1970-01-01
      • 2023-03-28
      • 2020-12-06
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多