【问题标题】:Custom Layout on UICollectionView using Swift 3使用 Swift 3 在 UICollectionView 上自定义布局
【发布时间】:2017-07-26 10:04:25
【问题描述】:
【问题讨论】:
标签:
ios
swift3
uicollectionview
uicollectionviewlayout
【解决方案1】:
有很多方法,并且有很多 3rd 方库可以提供帮助。但我怀疑你不知道如何在单元格之间进行布局和间距。
这是最好的帮助..只需使用值来获得类似的布局。
override func prepareLayout() {
// 1
if cache.isEmpty {
// 2
let columnWidth = contentWidth / CGFloat(numberOfColumns)
var xOffset = [CGFloat]()
for column in 0 ..< numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth )
}
var column = 0
var yOffset = [CGFloat](count: numberOfColumns, repeatedValue: 0)
// 3
for item in 0 ..< collectionView!.numberOfItemsInSection(0) {
let indexPath = NSIndexPath(forItem: item, inSection: 0)
// 4
let width = columnWidth - cellPadding * 2
let photoHeight = delegate.collectionView(collectionView!, heightForPhotoAtIndexPath: indexPath,
withWidth:width)
let annotationHeight = delegate.collectionView(collectionView!,
heightForAnnotationAtIndexPath: indexPath, withWidth: width)
let height = cellPadding + photoHeight + annotationHeight + cellPadding
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
let insetFrame = CGRectInset(frame, cellPadding, cellPadding)
// 5
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
// 6
contentHeight = max(contentHeight, CGRectGetMaxY(frame))
yOffset[column] = yOffset[column] + height
column = column >= (numberOfColumns - 1) ? 0 : ++column
}
}
}
参考UIcollectionView Layout