我正在尝试实现一个表格视图单元,显示代表家庭设施(例如毛巾、wifi、洗衣房等)的一系列图标。单元格可能会显示大量设施(取决于家中拥有多少设施),因此我将最多显示三个,并指示如果超过三个,则可以点击单元格查看更多。这是它应该看起来的样子(来自Airbnb的应用程序):
我试图通过在表格视图单元中动态添加UIImageViews到UIStackView来完成此操作。我使用了alignment设置为“填充”和distribution设置为“平均间距”的UIStackView,其想法是无论我添加多少图标,堆栈视图都会均匀地排列它们。
我在Storyboard中设置了stack view。它与其内容视图的顶部、底部、左侧和右侧边缘约束相关联,以便它填充表格视图单元,直到边缘。
这是我尝试使用的代码动态向单元格添加UIImageViews的方式。请注意,“amenities”是一个字符串数组,等于我的图像资源文件夹中图标的名称:
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++
}
图像视图的背景是蓝色的,而堆栈视图的背景颜色是绿色的。下面是一个例子,其中房屋有三种设施:
![enter image description here](https://istack.dev59.com/3h2NU.webp)
addArrangedSubview
。 - dan