ios - 当我缩小表格 View 并滚动时,表格 View 无法正确呈现

标签 ios uitableview

我正在 Xcode 中使用表格 View ,其中包含带有文本字段元素的自定义单元格。如果我的表格扩展到不需要滚动的位置,那么它可以完美工作,但我试图让我的表格在用户按下回车键后向下滚动到下一个单元格,以便它可以更小。

返回部分的向下滚动实际上工作正常,问题是,根据我将表格 View 制作得有多小,它将用添加到的用户输入替换 textField.text 元素下面的可变数量的单元格前一个单元格。我不知道为什么会这样。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
    cell.id = indexPath.item
    cell.tag = indexPath.item
    cell.n.tag = indexPath.item

    return cell
}

image

最佳答案

当前的 cellForRowAt 实现中没有重置 textField 值。一旦用户在其中一个单元格中输入文本,它就会保留在那里,并且由于单元格不断被重复使用,看起来文本只是随机出现在周围。

用户输入的值必须存储在某处。例如。有一个字典 var userInput = [Int: String]()。将 UITextFieldDelegate 协议(protocol)添加到您的 Controller 并实现以下内容:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let newText = (textField.text as? NSString)?.replacingCharacters(in: range, with: string)
    userInput[textField.tag] = newText // store entered text

    return true
}

然后只需用它更新cellForRowAt:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell:MyCustomCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! MyCustomCell
    cell.id = indexPath.item
    cell.tag = indexPath.item
    cell.n.tag = indexPath.item

    // update cell's textfield text
    cell.textField.delegate = self
    cell.textField.tag = indexPath.item
    cell.textField.text = userInput[indexPath.item]

    return cell
}

关于ios - 当我缩小表格 View 并滚动时,表格 View 无法正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203007/

相关文章:

ios - 在 Swift 中使用自动布局时获取错误的 tableVIew.contentSize

ios - 如何 Hook UITableViewCell/UICollectionViewCell 的 init 方法?

ios - 打印出一个字符串的所有组合

ios - 如何在 objective-c 中使用 Realm.io 通过主题标签过滤帖子?

ios - 获取表的索引路径

uitableview - 使用EGOTableViewPullRefresh更新表

objective-c - 处理推送到不同 View 的通知

ios - 静态 subview 背景图片效果

iphone - 应用程序在设备上运行时卡在特定 View 上

objective-c - UITableViewCell高度计算和委托(delegate)?