0

如何获得interItemSpacing水平流布局的实际值UICollectionView?我能得到(和设置)的唯一信息是minimumInteritemSpacing.

为了以下小计算,我需要它来始终在集合视图中显示 3 个等宽的项目,而不管屏幕大小(我想minimumInteritemSpacing用公式中的 interItemSpacing 的当前值替换): flowLayout.itemSize = CGSizeMake((_collectionView.frame.size.width/3.0)-(flowLayout.minimumInteritemSpacing/3.0), _collectionView.frame.size.height);我把这个计算放进去viewDidLayoutSubviews,它不是精确地为某些屏幕工作,因为它们的电流interItemSpacing不同于minimumInteritemSpacing

提前致谢。

4

2 回答 2

3

您可以通过比较两个连续单元格来获得实际间距

就像是

let firstIndex =  IndexPath(item: 0, section: 0)
let secondIndex = IndexPath(item: 1, section: 0)
if let att1 = collectionView.layoutAttributesForItem(at: firstIndex),
let att2 = collectionView.layoutAttributesForItem(at: secondIndex) {
  let actualSpace = att2.frame.minX - att1.frame.maxX
  print (actualSpace)
}
于 2018-08-26T07:07:22.653 回答
1

要创建具有固定间距的单元格,请尝试以下操作:

private let minItemSpacing: CGFloat = 8
private let itemWidth: CGFloat      = 100
private let headerHeight: CGFloat   = 32

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Create our custom flow layout that evenly space out the items, and have them in the center
    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    layout.minimumInteritemSpacing = minItemSpacing
    layout.minimumLineSpacing = minItemSpacing
    layout.headerReferenceSize = CGSize(width: 0, height: headerHeight)

    // Find n, where n is the number of item that can fit into the collection view
    var n: CGFloat = 1
    let containerWidth = collectionView.bounds.width
    while true {
        let nextN = n + 1
        let totalWidth = (nextN*itemWidth) + (nextN-1)*minItemSpacing
        if totalWidth > containerWidth {
            break
        } else {
            n = nextN
        }
    }

    // Calculate the section inset for left and right. 
    // Setting this section inset will manipulate the items such that they will all be aligned horizontally center.
    let inset = max(minItemSpacing, floor( (containerWidth - (n*itemWidth) - (n-1)*minItemSpacing) / 2 ) )
    layout.sectionInset = UIEdgeInsets(top: minItemSpacing, left: inset, bottom:    minItemSpacing, right: inset)

    collectionView.collectionViewLayout = layout
}

欲了解更多信息,这篇优秀的文章:

http://samwize.com/2015/11/30/understanding-uicollection-flow-layout/

于 2016-04-13T13:22:45.277 回答