ios - 在 UITableView 中快速滚动并选择单元格时,文本字段委托(delegate)将 indexPath 返回为 nil 并崩溃

标签 ios uitableview uitextfield swift3 uitextfielddelegate

我有这样的 TableViewController 结构(提到委托(delegate)目的):

----View
-----Scroll View
------Content View
-------TableView
--------TableViewCell

我可以正确加载 TableView 的所有行和部分。每个 TableViewCell 都有一个可编辑的 UITextField。当用户开始编辑 UITextField 时,我需要能够检索用户键入的内容。要更新正确的数据集,我目前的做法是检索 UITextField

indexPath

我的问题是:当我缓慢滚动并逐一单击 UITextField 时,我不会崩溃。但是,如果我单击一个单元格并快速向下滚动(即使我停留在同一个 部分),我会因为 indexPath 为空而崩溃。

在我的代表中我有这个:

func textFieldDidEndEditing(_ textField: UITextField) {
    //here is the code I am using to determine the indexPath
    let view = textField.superview!
    let cell = view.superview as! UITableViewCell
    let viewController = ShowPointsViewController() //this is the name of my ViewController
    let textFieldIndexPath = PointSourcesTV.indexPath(for: cell) //this is the name of my TableView

    print(textFieldIndexPath) //Returns nil here if I scroll too quickly
    let key = tableHeaders[(textFieldIndexPath?.section)!]
}

最佳答案

我不确定您是否使用正确的方法获取 UITextFieldindexPath,这可能会导致崩溃。但是你可以在你的 cellForRowAtIndexPath 中尝试类似的东西你可以将 UITextField 的标签设置为 indexPath.row 然后获取单元格实例使用-

let cell = PointSourcesTV.cellForRowAtIndexPath(IndexPath(row: textField.tag, section: 0)) as! UITableViewCell

关于ios - 在 UITableView 中快速滚动并选择单元格时,文本字段委托(delegate)将 indexPath 返回为 nil 并崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40623489/

相关文章:

ios - UITextFieldViewModeWhileEditing 更改我的 TextField 框架

ios - 如何控制 UITextField 的复制和粘贴弹出位置?

ios - 如何中止 iOS 中的手势?

ios - 将 Box2D 物理应用于 UIView 与 CALayer

iphone - UITableView 的单个 View 中存在多少个单元格?

Swift 如何将 Parse createdAt 时间转换为时间前?

ios - 按值 Swift 将数组拆分为数组

ios - XCode 6.1 可能的索引错误?

ios - 如何使用类似选择器的自定义编辑模式创建 UITableView

ios - 在输入击键时获取 UITextField 的值?