首页 > 解决方案 > 4 个单元格中仅添加了 1 个子视图

问题描述

代码如下

class TableViewController: UITableViewController, UITextFieldDelegate {

let fruitsComponents: [String] = ["Apple", "Banana", "Grape", "Pear"]

let fruitsTextField = UITextField(frame: CGRect(x: 100, y: 7.5, width: 50, height: 30))

override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 4
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "fruitsCell", for: indexPath)

    cell.textLabel?.text = fruitsComponents[indexPath.row]
    fruitsTextField.backgroundColor = UIColor.darkGray
    fruitsTextField.delegate = self

    cell.addSubview(fruitsTextField)

    return cell
}

1节还行。

4行还行。

单元格的标题是 Apple、Banana、Grape、Pear ok。

但只有 1 个子视图被添加到第 4 行的“梨”中。

问题1。为什么不将 3 个子视图添加到行中?

问题2。如何为所有行添加子视图?

谢谢

标签: swiftuitableview

解决方案


由于您只有一个 fruitsTextField 实例,因此它只能是一行的子视图。所以,

  • 当您将其添加到第 2 行时,它将从第一行中删除
  • 当您将其添加到第 3 行时,它将从第二行中删除

等等。

主要问题是,您不应该在每次cellForRow调用时都添加子视图,因为单元格正在被重用,因此即使每个单元格都有不同的文本视图,您最终可能会在每个调用中添加多个文本视图细胞。

最好创建自己的自定义UITableViewCell子类,将文本视图作为子视图,连接插座并继续使用它。您可以在网上找到几个示例,只需检查“UITableViewCell 子类”


推荐阅读