swift - 如何在单元格之间获得更均匀的垂直距离?

标签 swift layout autolayout uicollectionviewcell

我已经使用自动布局动态创建单元格(没有 Storyboard或 xib),但布局管理器似乎是 将单元格配对,使一个矮的和一个高的单元格并排组成一排。

screenshot

我想要的是让单元格之间的距离均匀(垂直堆叠),而不是大的空隙。因此,左侧向下的三个连续短单元格的高度和位置可能与右侧的一个大单元格相同。换句话说:所有单元格之间的垂直距离统一。

  /// 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。它让我更接近我的目标,但看起来单元格的数量按列平均分配,所以如果最左边的列有短单元格,它会“早”用完单元格并且左侧有很多空间底部。看来我可能需要按大小对单元格进行排序以获得更好的分布。

second version

最佳答案

遵循 https://www.raywenderlich.com/392-uicollectionview-custom-layout-tutorial-pinterest 中的代码

您可以将 UICollectionViewFlowLayout 子类化以获得所需的内容。

这是它的主要代码。 注:代码来自上述网站

import UIKit

protocol PinterestLayoutDelegate: class {
  // 1. Method to ask the delegate for the height of the image
  func collectionView(_ collectionView:UICollectionView, heightForPhotoAtIndexPath indexPath:IndexPath) -> CGFloat
}

class PinterestLayout: UICollectionViewLayout {
  //1. Pinterest Layout Delegate
  weak var delegate: PinterestLayoutDelegate!

  //2. Configurable properties
  fileprivate var numberOfColumns = 2
  fileprivate var cellPadding: CGFloat = 6

  //3. Array to keep a cache of attributes.
  fileprivate var cache = [UICollectionViewLayoutAttributes]()

  //4. Content height and size
  fileprivate var contentHeight: CGFloat = 0

  fileprivate var contentWidth: CGFloat {
    guard let collectionView = collectionView else {
      return 0
    }
    let insets = collectionView.contentInset
    return collectionView.bounds.width - (insets.left + insets.right)
  }

  override var collectionViewContentSize: CGSize {
    return CGSize(width: contentWidth, height: contentHeight)
  }

  override func prepare() {
    // 1. Only calculate once
    guard cache.isEmpty == true, let collectionView = collectionView else {
      return
    }
    // 2. Pre-Calculates the X Offset for every column and adds an array to increment the currently max Y Offset for each column
    let columnWidth = contentWidth / CGFloat(numberOfColumns)
    var xOffset = [CGFloat]()
    for column in 0 ..< numberOfColumns {
      xOffset.append(CGFloat(column) * columnWidth)
    }
    var column = 0
    var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)

    // 3. Iterates through the list of items in the first section
    for item in 0 ..< collectionView.numberOfItems(inSection: 0) {

      let indexPath = IndexPath(item: item, section: 0)

      // 4. Asks the delegate for the height of the picture and the annotation and calculates the cell frame.
      let photoHeight = delegate.collectionView(collectionView, heightForPhotoAtIndexPath: indexPath)
      let height = cellPadding * 2 + photoHeight
      let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
      let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)

      // 5. Creates an UICollectionViewLayoutItem with the frame and add it to the cache
      let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
      attributes.frame = insetFrame
      cache.append(attributes)

      // 6. Updates the collection view content height
      contentHeight = max(contentHeight, frame.maxY)
      yOffset[column] = yOffset[column] + height

      column = column < (numberOfColumns - 1) ? (column + 1) : 0
    }
  }

  override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var visibleLayoutAttributes = [UICollectionViewLayoutAttributes]()

    // Loop through the cache and look for items in the rect
    for attributes in cache {
      if attributes.frame.intersects(rect) {
        visibleLayoutAttributes.append(attributes)
      }
    }
    return visibleLayoutAttributes
  }

  override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    return cache[indexPath.item]
  }

}

关于swift - 如何在单元格之间获得更均匀的垂直距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54049343/

相关文章:

ios - 如何使用 PKAddPassButton 添加 "Add to Apple Wallet"按钮 - swift

firefox - <a> 可以包含 HTML5 中的 &lt;footer&gt; 吗?

iOS/自动布局/ Storyboard : Pin view not responsive for table header

swift - 如何恢复到旧 Swift 的 AnyObject 和 Any 自动转换行为?

swift - 从 Sprite Kit 中关闭邮件 View Controller

objective-c - 如何在 Swift 中实现这个多行字符串字面量宏?

android - 多行 TextView 的 wrap_content 宽度

ios - 如何在 facebook 应用程序的顶部栏等 UIButton 文本下方添加一行。?

长表格的 iOS AutoLayout