gpt4 book ai didi

ios - 如何在 UITableView 或 UICollectionView 中使用变量 UIStackView?

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:27 26 4
gpt4 key购买 nike

我目前正在使用 UICollectionView 构建通用表单生成器。

每个表单元素都是一个单元格,对于复选框,我在单元格内使用 UIStackView 来显示所有可用选项。

问题是每次我重复使用该单元格时,即使我删除了所有 arrangedSubviews,它们也会留在新 View 中。

下面的代码是我正在做的一个简化版本:

class cell: UICollectionViewCell {

@IBOutlet weak var stackView: UIStackView!

func setup(options: [String]) {

for option in options {
let label = UILabel()
label.text = option
stackView.addArrangedSubview(label)
}

}

override func prepareForReuse() {
super.prepareForReuse()
optionsStackView.arrangedSubviews.forEach({ optionsStackView.removeArrangedSubview(view: $0) })
}

}

取而代之的是,我目前的解决方法是在 prepareForReuse() 中隐藏()每个 arrangedSubview,而不是删除它们,但我不喜欢那样。

最佳答案

如果您阅读有关 removeArrangedSubview 方法的 Xcode 文档,他们会说:

Discussion: This method removes the provided view from the stack’sarrangedSubviews array. The view’s position and size will no longer bemanaged by the stack view. However, this method does not remove theprovided view from the stack’s subviews array; therefore, the view isstill displayed as part of the view hierarchy.

To prevent the view from appearing on screen after calling the stack’sremoveArrangedSubview: method, explicitly remove the view from thesubviews array by calling the view’s removeFromSuperview() method, orset the view’s isHidden property to true.

因此您还需要从堆栈 View 中删除 subview 。 (当我第一次开始使用堆栈 View 时,我也为此苦苦挣扎。)

编辑:

事实上,正如@kid_x 指出的那样,只需使用 removeFromSuperView() 删除 subview 即可。我不确定 removeArrangedSubview() 的意义是什么,TBH。


编辑#2:

我建议完全不要使用 removeArrangedSubview()。相反,请执行以下操作之一:

选项 1:如果您需要从堆栈 View 中永久删除 View ,只需使用 removeFromSuperView()

选项 2:如果您想从堆栈 View 中删除 View ,然后再将它们放回去,只需切换 subview 的 isHidden 属性,如 suprandr 的回答中所述。堆栈 View 将关闭空白空间并重新定位剩余的 View ,就像您删除它们一样。

关于ios - 如何在 UITableView 或 UICollectionView 中使用变量 UIStackView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953402/

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