繁体   English   中英

使用Swift 3在UICollectionView上自定义布局

[英]Custom Layout on UICollectionView using Swift 3

CollectionView上的需求布局

我在Swift 3.0的collectionview上无法实现自定义布局。 在相似的布局上搜索已经过了两天,但我找不到。 请任何人帮助我实现我期望的自定义​​布局。

这样做的方法很多,而且有很多第三方提供帮助。 但是我怀疑您不知道如何在单元格之间进行布局和间距。

这是最好的帮助。仅需使用值即可获得相似的布局。

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布局

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM