swift - 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。如何为所有行添加子视图?
谢谢
解决方案
由于您只有一个 fruitsTextField 实例,因此它只能是一行的子视图。所以,
- 当您将其添加到第 2 行时,它将从第一行中删除
- 当您将其添加到第 3 行时,它将从第二行中删除
等等。
主要问题是,您不应该在每次cellForRow
调用时都添加子视图,因为单元格正在被重用,因此即使每个单元格都有不同的文本视图,您最终可能会在每个调用中添加多个文本视图细胞。
最好创建自己的自定义UITableViewCell
子类,将文本视图作为子视图,连接插座并继续使用它。您可以在网上找到几个示例,只需检查“UITableViewCell 子类”
推荐阅读
- java - 如何使用 DB 数据动态添加或删除 spring 框架的调度程序(服务器处于运行状态)?
- postgresql - 我无法在 PostgreSQL 中创建视图
- bash - ssh 和 sudo su 在不提示输入密码的情况下获取交互式终端
- exoplayer - ExoPlayer 如何确定其缓冲速度?
- ruby-on-rails - 从日文字符中删除粗体样式
- swift - 如何解决这个涉及函数和选项的问题?
- android - 调试到设备时Android资源编译失败
- xcode - 提出警报
- r - 如何找到 R 中矩生成函数 (MGF) 的一阶导数以进行 Gamma 分布?
- excel - Excel 如何将 Worksheetfunction 定义为“全局”对象,以便任何函数都可以通过简单别名访问它