【发布时间】:2019-05-31 15:20:57
【问题描述】:
我已经使用自动布局(没有故事板或 xib)动态创建单元格,但布局管理器似乎是 将单元格配对,使一个短单元格和一个高单元格并排组成一排。
我想要的是让单元格之间的距离一致(垂直堆叠),而不是大的空白。因此,在左侧向下的三个连续短单元的高度和位置可能与右侧的一个大单元相同。换句话说:所有单元格之间的垂直距离一致。
/// Everything is a side effect. Configure the cell passed in
///
/// - Parameters:
/// - cell: cell to format
/// - indexPath: index of cell
func formatAutolayoutCell(cell: AutoResizingTextCell, at indexPath: IndexPath) {
let event = eventsSource[indexPath.row]
cell.layer.borderColor = event.calendar.cgColor
cell.contentView.backgroundColor = UIColor(cgColor: event.calendar.cgColor).withAlphaComponent(0.1)
cell.titleLabel.text = event.title
cell.contentView.addSubview(cell.titleLabel)
cell.titleLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
cell.titleLabel.widthAnchor.constraint(equalToConstant: cellWidth).isActive = true
cell.titleLabel.textColor = UIColor(cgColor: event.calendar.cgColor)
cell.titleLabel.textAlignment = .center
cell.contentView.addSubview(cell.bodyLabel)
cell.bodyLabel.text = event.notes ?? ""
cell.bodyLabel.widthAnchor.constraint(equalToConstant: cellWidth).isActive = true
cell.bodyLabel.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
cell.titleLabel.bottomAnchor.constraint(equalTo: cell.bodyLabel.topAnchor).isActive = true
}
编辑:
使用Galo Torres Sevilla 的建议,我尝试使用UICollectionViewLayout。它让我更接近我的目标,但看起来单元格的数量是按列平均划分的,所以如果最左边的列有短单元格,它会“提前”用完单元格,左侧有很多空间底部。看来我可能需要按大小对单元格进行排序以获得更好的分布。
【问题讨论】:
-
您将无法使用 autoLayout 执行此操作。我的建议是您将
UICollectionViewFlowLayout子类化并从那里工作以获得您想要的布局。这是一个可能对您有用的示例。 raywenderlich.com/… -
看起来很完美。如果您想以您的答案不仅仅是链接的方式将其写成答案(因为不允许仅链接的答案),我很乐意投票并接受它。你已经完成了一半以上。
-
出色的工作让您的布局!你很快就明白了。我会在下面留下答案
-
感谢您的帮助!我已经深入研究了代码,所以我读到的东西是有道理的。另外,我下定决心要有所作为!
标签: swift layout autolayout uicollectionviewcell