首页 > 解决方案 > UIStackView 在 tableView Cell didSet 中添加排列子视图

问题描述

在我的 tableView Cell 类中,我使用 didSet 方法来设置我的 UI 值,在那里我有一个来自 api 的字符串数组,我用它来创建一个按钮数组并将其附加到 UIStackView

var pollDataInPollCell: PollModel? {
    didSet{
        if let pollOptions = pollDataInPollCell?.poll_detail {
           //sample pollOptions = ["Button1","Button2","Button3","Button4"]
            for index in pollOptions {
                let bt = UIButton(type: .system)
                bt.setTitleColor(.blue, for: .normal)
                bt.setTitle(index, for: .normal)
                optionBtnStackView.addArrangedSubview(bt)
            }
        }
    }
}

我在 didSet 之外的 stackView

var optionBtnStackView: UIStackView = {
    let sv = UIStackView()
    sv.axis = .vertical
    sv.distribution = .fillEqually
    sv.spacing = 5
    return sv
}()

启动时一切正常,但是,当我向下和向上滚动时,我的 stackview 又添加了 4 个按钮。它在启动时有 4 个,然后是 8 个,然后是 12 个,并且每当我上下滚动我的应用程序时,它都会增加 4 个。我知道问题出在 tableView dequeueReusableCell 但我找不到解决此问题的方法。有什么建议么?谢谢你。

标签: swiftuitableviewuistackview

解决方案


在您的 didSet 中使用以下代码

var pollDataInPollCell: PollModel? {
    didSet{
        for view in optionBtnStackView.subviews {
            optionBtnStackView.removeArrangedSubview(view)
            view.removeFromSuperview()
        }
        if let pollOptions = pollDataInPollCell?.poll_detail {
           //sample pollOptions = ["Button1","Button2","Button3","Button4"]
            for index in pollOptions {
                let bt = UIButton(type: .system)
                bt.setTitleColor(.blue, for: .normal)
                bt.setTitle(index, for: .normal)
                optionBtnStackView.addArrangedSubview(bt)
            }
        }
    }
}

推荐阅读