ios - swift3 scrollToRow 即使有空单元格

标签 ios swift uitableview uiscrollview swift3

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

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

我的代码是这样的:

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

}

最佳答案

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

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

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

然后使用 contentOffset 设置您希望内容在 ScrollView 中的初始位置:

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

您可以在以下网址获得更多信息:https://developer.apple.com/reference/uikit/uiscrollview

希望对您有所帮助。

关于ios - swift3 scrollToRow 即使有空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39874279/

相关文章:

ios - Twitter是否为第三方ios应用提供社交登录选项,迅速

ios - 正确使用 Metal 的方法

ios - 从 NSDictionary 对象的 NSArray,如何获得 uniques 的 NSArray

ios - 在拒绝 UIActivityController 的“保存图像”权限后,如何将用户重定向到设置?

ios - 如何根据按下的按钮选择行?

ios - 如何使用 Swift 4.2 在 TableView 中创建 JSON 可编码结构数据的搜索功能?

ios - 在 iOS 上下载和解析 JSON 工具包

c++ - 如何在 swift 项目中使用 c++ 库来制作更好的 glsl 编译器

ios - Swift SubView 在 tableView 前面

ios - 从 Obj-C 中调用静态 Swift 方法