KevinVuD
KevinVuD

Reputation: 611

UIStackView add arrange subviews inside tableView Cell didSet

In my tableView Cell class, I use didSet method to setup my UI values and in there I have an array of string from api which I use to create an array of buttons and append it to a 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)
            }
        }
    }
}

my stackView outside of didSet

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

everything works great at launch however, when I scroll down and up, my stackview is adding 4 more buttons. It has 4 at launch and then 8 and then 12 and keep increasing by 4 whenever I scroll up and down my app. I know the problem is from tableView dequeueReusableCell but I couldn't find a way to fix this issue. Any suggestions? Thank you.

Upvotes: 0

Views: 422

Answers (1)

Deepika
Deepika

Reputation: 468

Use below code in your 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)
            }
        }
    }
}

Upvotes: 1

Related Questions