我试图通过动态地将UIImageViews添加到表视图单元格中的UIStackView来实现此目的.我正在使用UIStackView,对齐设置为“Fill”,分布设置为“Equal spacing”,这个想法是堆栈视图将均匀地分隔图标,无论我添加多少.
我在Storyboard中设置了堆栈视图.它对内容视图的顶部,底部,左侧和右侧边距有约束,因此它填充表格视图单元格,直到边距.
这是我用来尝试动态地将UIImageViews添加到单元格的代码.注意便利设施是一个字符串数组,等于我的图像资源文件夹中的图标名称:
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++ }
图像视图的背景为蓝色,堆栈视图的背景颜色为绿色.这是结果,对于一个房子有三个设施的情况:
看起来所有图像视图都被推到屏幕左侧.它们还从上到下填充单元格的内容视图,即使堆栈视图固定到内容视图边距.看不到绿色,因此堆栈视图似乎没有固定到单元格的边缘.
知道这里有什么问题吗?
解决方法
但请注意:如果从UIStackView上的arrangementsSubviews数组中删除视图,它仍然是子视图.从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.
从文档开始总是一个好主意.