滚动时自定义UITableViewCell会发生更改

时间:2017-03-19 10:21:02

标签: ios swift uitableview

我有一个条形按钮项,它使用递增的整数变量插入新行:

enter image description here

class TableViewController: UITableViewController {

    var personNo = 0
    var data = [String]()

    @IBAction func addPerson(_ sender: UIBarButtonItem) {

        personNo += 1

        tableView.beginUpdates()
        data.append("Person \(personNo)")

        tableView.insertRows(at: [IndexPath(row: data.count - 1, section: 0)], with: .automatic)

        tableView.endUpdates()

    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "newPerson") as! CustomCell

        cell.lblPerson?.text = "Person \(personNo): "

        // Configure the cell...

        return cell
    }
}

添加行有效,但滚动表视图时单元格的值会更改:

enter image description here

为什么会发生这种情况?如何保存每个单元格的状态?

2 个答案:

答案 0 :(得分:1)

您需要从数据源数组(data

获取数据

替换

cell.lblPerson?.text = "Person \(personNo): "

cell.lblPerson?.text = data[indexPath.row]

旁注:为了您的目的,我建议您使用自定义模型,例如:

struct Person {
    var name : String
    var amount : Double
}

答案 1 :(得分:1)

您只有一个personNo变量,因此在为滚动生成单元格时,会使用当前值personNo

您可以使用indexPath.row值:

cell.lblPerson?.text = "Person \(indexPath.row+1): "
相关问题