UIStackView在tableView单元格didSet内添加安排子视图

时间:2018-09-17 23:22:14

标签: swift uitableview uistackview

在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,但是我找不到解决此问题的方法。有什么建议么?谢谢。

1 个答案:

答案 0 :(得分:1)

在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)
            }
        }
    }
}