在UITableView中以编程方式将UIViews添加到UIStackView

问题描述 投票:0回答:1

我在列表中有三个元素UILabelUIImageViewUIButton。我必须在UITableView内相应地展示它们。我有这样一个数组:

tableArray = [["label", "img", "button"],["img","button","label"],["img","label","button"],["button", "img", "label"]]

元素的位置与数组内的位置(索引)相同。我的cellForRowAt看起来像这样:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else {
        return UITableViewCell()
    }

    let tableData = tableArray[indexPath.row]

    var count = 0
    tableData.forEach { (element) in
        switch element {
        case "label":
            let lbl = self.createLabel()

            cell.stackView.insertArrangedSubview(lbl, at: count)
            count += 1
            break
        case "img":
            let img = self.createImage()
            cell.stackView.insertArrangedSubview(img, at: count)
            count += 1
            break
        case "button":
            let btn = self.createButton()
            cell.stackView.insertArrangedSubview(btn, at: count)
            count += 1
            break
        default:
            break
        }
    }
    return cell
}

每当我将这些项目添加到单元格中时,每当我滚动TableView时,问题就出现了。

我尝试过几种解决方案但没有运气。

  1. 然后qazxsw poi将元素添加到堆栈视图中。
  2. if tableView.cellForRow(at: indexPath) == nil之后检查if cell == nil。如果没有那么dequeueReusableCell细胞。
  3. init甚至在没有let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil) as? FirstTableViewCell的情况下尝试过。

但每次都会发生同样的事情。

这是dequeueReusableCell

FirstTableViewCell

任何想法如何检查元素是否已添加到class FirstTableViewCell: UITableViewCell { @IBOutlet weak var stackView: UIStackView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } ,然后我不会添加它们。

ios uitableview uistackview reuseidentifier
1个回答
1
投票

因为单元格被重用,所以你需要在StackView中做的第一件事就是“重置”你的单元格...换句话说,从堆栈视图中清除现有的子视图:

cellForRowAt

现在,基于您提供的代码,如果单元格总是包含override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else { return UITableViewCell() } // remove the views that are currently in the stack cell.stackView.arrangedSubviews.forEach { $0.removeFromSuperview() } // the rest of your setup let tableData = tableArray[indexPath.row] var count = 0 tableData.forEach { (element) in ... } UILabelUIImageView,只是在不同的顺序和不同的属性,您可以在创建单元格时添加它们一次(或者如果你在单元格原型中添加它们'使用一个),然后根据需要简单地重新安排它们。

© www.soinside.com 2019 - 2024. All rights reserved.