【问题标题】:UIStackView add arrange subviews inside tableView Cell didSetUIStackView 在 tableView Cell didSet 中添加排列子视图
【发布时间】:2018-09-17 23:22:14
【问题描述】:

在我的 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 中,您正在向 optionBtnStackView 添加视图。当单元格出列时,它的 optionBtnStackView 已经添加了排列视图,然后在它的顶部,在 didSet 中,您正在向它添加更多。每次单元格出列时,请尝试从 optionBtnStackView 中删除所有视图,然后添加新视图。

标签: swift uitableview uistackview


【解决方案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)
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多