gpt4 book ai didi

ios - 以编程方式将 subview 添加到 UIStackView

转载 作者:IT王子 更新时间:2023-10-29 05:46:33 24 4
gpt4 key购买 nike

我正在尝试实现一个表格 View 单元格,该单元格显示一系列代表家庭便利设施(例如毛巾、wifi、洗衣等)的图标。该单元格可能会显示大量便利设施(取决于房屋的数量),因此我将最多显示三个,并表示如果超过三个,您可以通过单击单元格查看更多。它应该是这样的(来自 Airbnb 的应用程序):

enter image description here

我试图通过将 UIImageViews 动态添加到 TableView 单元格中的 UIStackView 来实现这一点。我使用的 UIStackView 的对齐设置为“填充”,分布设置为“等距”,想法是无论我添加多少个图标,堆栈 View 都会均匀地隔开图标。

我在 Storyboard 中设置了堆栈 View 。它对其内容 View 的顶部、底部、左侧和右侧边距 有约束,因此它会填充表格 View 单元格,直到边距。

这是我用来尝试将 UIImageView 动态添加到单元格的代码。注意 amenities 是一个字符串数组,等于我的图像 Assets 文件夹中图标的名称:

        cell.stackView.backgroundColor = UIColor.greenColor()
var i = 0
while (i < amenities.count && i < 4) {
if (i < 3) {
let imageView = UIImageView(image: UIImage(named: amenities[i]))
imageView.contentMode = .ScaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor.blueColor()

// Add size constraints to the image view
let widthCst = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
imageView.addConstraint(widthCst)

// Add image view to stack view
cell.stackView.addSubview(imageView)
} else {
// Add a label to the stack view if there are more than three amenities
let label = UILabel()
label.text = "\(amens.count - i) more"
label.textAlignment = NSTextAlignment.Left
cell.stackView.addSubview(label)
}
i++
}

ImageView 的背景为蓝色,堆栈 View 的背景色为绿色。以下是结果,对于房子具有三种便利设施的情况:

enter image description here

看起来所有 ImageView 都被推到屏幕左侧。它们还从上到下填充单元格的内容 View ,即使堆栈 View 被固定到内容 View 边距。看不到绿色,因此堆栈 View 似乎没有固定在单元格的边缘。

知道这里出了什么问题吗?

最佳答案

正如 Dan 在评论中所说,使用 addArrangedSubview 添加一个 subview ,该 subview 将由 UIStackView 自动布局。

但是请注意:如果您从 UIStackView 的 arrangedSubviews 数组中删除一个 View ,它仍然是一个 subview 。来自 UIStackView 文档:

The stack view ensures that its arrangedSubviews property is always a subset of its subviews property. Specifically, the stack view enforces the following rules:

• When the stack view adds a view to its arrangedSubviews array, it also add that view as a subview, if it isn’t already.

• When a subview is removed from the stack view, the stack view also removes it from the arrangedSubviews array.

• Removing a view from the arrangedSubviews array does not remove it as a subview. The stack view no longer manages the view’s size and position, but the view is still part of the view hierarchy, and is rendered on screen if it is visible.

从文档开始总是一个好主意。

关于ios - 以编程方式将 subview 添加到 UIStackView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36463021/

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