table 视图单元格中的堆栈视图

Stack View in a table view cell

我正在尝试以编程方式在 table 视图单元格内实现堆栈视图,并向其添加标签和按钮,如下所示:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    let dict = self.char[indexPath.row]
    let stackView = UIStackView()
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .horizontal
    stackView.spacing = 20
    stackView.distribution = .fillProportionally
    stackView.alignment = .leading
    cell.addSubview(stackView)
    NSLayoutConstraint.activate([
        stackView.leadingAnchor.constraint(equalTo: cell.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: cell.trailingAnchor)
        ])
    let bornLabel = UILabel()
    bornLabel.textColor = UIColor.blue
    let bornLabelValue = UILabel()
    bornLabelValue.textColor = UIColor.blue
    stackView.addArrangedSubview(bornLabel)
    stackView.addArrangedSubview(bornLabelValue)
    for (key, value) in dict {
        bornLabel.text = key
        bornLabelValue.text = value
        if key == "Height" {
            let button = UIButton(type: .roundedRect)
            button.setTitle("English", for: .normal)
            button.setTitleColor(.blue, for: .normal)
         stackView.addArrangedSubview(button)
        }
    }
    return cell
}

问题是每次调用 tableView.reloadData() 时,都会在现有单元格之上添加另一个单元格,每个标签的值都不同,具体取决于提供给 tableView 的数据。或者它可能不会每次都生成另一个单元格,而只是添加另一个堆栈视图。我不确定。我该如何解决这个问题?

谢谢

问题是您得到一个“可重复使用的单元格”,这意味着前几次它会是一个空单元格,然后它会变成一个您已经在其中添加了 UIStackView.

的单元格

您应该通过 Storyboard 或新的 XIB 文件创建一个新的原型单元格,在其中添加 UIStackView,然后仅在您的 cellForRowAt indexPath:实施。

或者您可以在技术上在 stackView 中设置一个标签,然后检查该标签的单元格……但请不要这样做。

尝试在cell.contentView

中添加stackView

我是 objective-C 人所以还没学会 swift。

在 Objective C 中,我们在实例化之前检查 cell 是否为 nil 的条件。

例如

if(cell == nil)
{
   # Instantiate cell here
}

此单元格不会为 indexPath 的每一行实例化。