【发布时间】:2020-03-29 16:24:14
【问题描述】:
我希望创建一个如下所示的 uicollectionview。
单元格的高度将保持不变,但宽度应根据标签文本的长度自动改变。
流式布局:
func prepareFlowLayout() -> UICollectionViewFlowLayout{
let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
flowLayout.minimumInteritemSpacing = 3
flowLayout.minimumLineSpacing = 3
return flowLayout
}
标签:
let nameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
//label.backgroundColor = .black
return label
}()
单元格内自动布局:
backgroundColor = .green
let conView = contentView
layer.cornerRadius = 5
clipsToBounds = true
conView.addSubview(nameLabel)
NSLayoutConstraint.activate([
nameLabel.centerXAnchor.constraint(equalTo: conView.centerXAnchor, constant: 0),
nameLabel.centerYAnchor.constraint(equalTo: conView.centerYAnchor, constant: 0),
nameLabel.heightAnchor.constraint(equalTo: conView.heightAnchor, multiplier: 0.8),
nameLabel.widthAnchor.constraint(equalTo: conView.widthAnchor, multiplier: 0.8)
])
任何人都可以向我发送正确的方向以找到实现此目标的方法吗?
【问题讨论】:
-
在这种情况下,您的单元格的大小适合其内容,但您需要它们占用额外的空间(在我假设的单元格中平均分配)。您不能在单个单元格中执行此操作;您将需要继承 UICollectionViewLayout 并计算那里的属性,因为它可以同时考虑一行中的所有单元格。
标签: ios swift uicollectionview autolayout