swift - 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 但我找不到解决此问题的方法。有什么建议么?谢谢你。
解决方案
在您的 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)
}
}
}
}
推荐阅读
- python - tweepy - 使用光标时获取剩余的 Twitter api 速率限制
- android - 使用带有首选项的 NavController
- html - 如何使文本环绕图像而不留下空格或换行符?
- c# - 如何使用合约解析器和值提供者在反序列化期间自定义值设置
- image - 图像编号取决于显示图像的分区号
- javascript - 滚动上的动画计数器并非全部加载
- python - 类型错误:此 COM 对象无法自动化 makepy 过程 - 请为此对象手动运行 makepy
- reactjs - 如何导出类并在酶测试中使用它
- java - 如何使用 Swagger @RequestParam Map 记录
- laravel - 如何在我的刀片文件中使用我的 vue 组件中的选择