gpt4 book ai didi

swift - UIStackView 在 tableView Cell didSet 中添加排列 subview

转载 作者:行者123 更新时间:2023-11-28 14:13:04 25 4
gpt4 key购买 nike

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

最佳答案

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

关于swift - UIStackView 在 tableView Cell didSet 中添加排列 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com