在我的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)
}
}
}
}
我的stackView在didSet之外
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但我找不到解决此问题的方法。有什么建议?谢谢。
在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)
}
}
}
}