【问题标题】:UITableViewCell Data changes after scrollingUITableViewCell 滚动后数据变化
【发布时间】:2016-07-16 11:10:54
【问题描述】:

我正在 UITableViewCell 中创建一个表单,该表单在原型单元格中具有标签和文本字段。在此处查看其图像 TableView Story board Image。 我正在使用标识符来动态创建表单,我的代码是

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("protocell", forIndexPath: indexPath) as! UITableViewCell

    var lable = cell.viewWithTag(1) as! UILabel
    lable.text = details[indexPath.row]
    lable.textColor = UIColor.brownColor().colorWithAlphaComponent(0.7)

    var textfield = cell.viewWithTag(2) as! UITextField
    textfield.placeholder = "Enter \(details[indexPath.row])"
    self.arrayTextField.append(textfield)
    if details[indexPath.row] == "Name" {
        textfield.placeholder = "Enter First \(details[indexPath.row]) Middle \(details[indexPath.row]) Last \(details[indexPath.row]) "
    }
    textfield.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.2)

    return cell
}

现在的问题是我有 18 个字段,当我在字段中输入值并滚动视图以填充剩余字段时,字段中的值会发生变化。 请帮忙。

【问题讨论】:

  • 您需要在数据源中跟踪哪个文本字段有文本。因此,当tableView:(tableView:cellForRowAtIndexPath:) 中有一个时,你放它,否则,你放你的 placeHolder,因为单元格被重复使用。
  • 从不使用包含表格视图单元格的 UI 元素的数组 (arrayTextField)。这可能是你的问题的原因。考虑改进(数据源)模型的设计,更改模型中的数据并重新加载表格视图。
  • 跟踪数据源我正在使用arrayTextField@Larme 如何在数据源中跟踪以查看哪个文本字段有文本。我已经搜索过,但一无所获。
  • 文本字段数组是对模型-视图-控制器模式的滥用。这会导致您的问题。 不要那样做。您应该跟踪模型中的相应属性,该属性在cellForRowAtIndexPath 中设置文本字段的文本。

标签: ios iphone swift uitableview xcode6


【解决方案1】:

创建UITableViewCell 子类并覆盖prepeareForReuse 函数 - 将单元格转换为默认模式。

斯威夫特:

override func prepareForReuse() {
    super.prepareForReuse()

    //set cell to initial state here, reset or set values, etc.
}

根据您的评论 - 关于如何继承 UITableViewCell

import UIKit

class MyCustomCell: UITableViewCell {
     // things that you can do here:
     // initialise your properties here. (label, textfield. etc)
     // layout subviews.
     // override superclass APIs.
}

【讨论】:

  • 我是 iphone 应用程序开发的初学者,所以@Evegeny Karkan 可以告诉我如何创建子类。
【解决方案2】:
  1. 不要将文本字段存储在数组中,而是应该将数据源“详细信息”数组存储在数组中。
  2. 在文本字段中输入任何内容后,更新该 indexPath 的“详细信息”数组。
  3. 子类 UITableViewCell 并创建一个 CustomTableViewCell 并为您提供 IBOutlets 文本字段标签以及不让您的生活更轻松的内容
  4. 在您的 CustomTablewViewCell 上有一个方法,例如 updateWithDetails(details),以便很好地封装代码

【讨论】:

  • 我的 details 数组,包含字段的标签,所以我无法更新它。
  • 然后从数组中删除那些。您的详细信息数组应该包含一些对象,例如EmployeesDetails * employeeDetails,然后数组应该是employeeDetailsArray。然后对于每个 EmployeeDetails 可以将“信息”作为字符串而不是文本字段。您的数据源不应包含任何 UI 元素,请将它们分开。
  • 我的详细信息数组就像details = ["name","address", contactnumber",]等等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多