如何解决CollectionView上的自定义布局
我有一个单元格,其宽度取决于内容。现在内容分别如图所示。中间有一个很大的缝隙,很难看。
我跳来跳去的最终结果类似于下一张图片。我希望单元格之间的空间保持恒定,即使该特定行的末尾有一些巨大的空白。
解决方法
您可以为集合使用自定义布局,以在集合视图中对齐单元格。
class CustomCollectionViewLayout: UICollectionViewFlowLayout {
// function which will return attributes for elements...
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
// for section insets and item spacing...
sectionInset = UIEdgeInsets(top: 10,left: 5,bottom: 10,right: 5)
minimumLineSpacing = 15
// get original attributes of elements in collection view for further modification (in this case to align collection view cells to left side)...
guard let originalAttributes = super.layoutAttributesForElements(in: rect) else {
return nil
}
// margin for cells for spacing...
var leftMargin: CGFloat = sectionInset.left
// maxY property which helps in resetting leftMargin when cells switch to next line...
var maxY: CGFloat = -1.0
// modifying original attributes to align them on left side...
let attributes = originalAttributes.map { (attribute) -> UICollectionViewLayoutAttributes in
// reset leftMargin and maxY when cell will switch to next line...
if attribute.frame.maxY > maxY {
leftMargin = sectionInset.left
maxY = attribute.frame.maxY
}
// setting oring x for current attribute...
attribute.frame.origin.x = leftMargin
// appending width of attribute + line spacing to calculate origin x for next attribute
leftMargin += attribute.frame.width + minimumLineSpacing
// return attribute for current element
return attribute
}
// return attributes for all elements in collection view
return attributes
}
}
然后只需在视图控制器中就可以为集合视图设置此自定义布局,如下所示:
let layout = CustomCollectionViewLayout()
collectionView.collectionViewLayout = layout
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。