如何在interItemSpacing
中获得水平流布局的实际UICollectionView
?我能获得(和设置)的唯一信息是minimumInteritemSpacing
。
我需要它,为了以下小计算,总是在集合视图中显示3个相等宽度的项目,而不管屏幕大小(我想用公式中的interItemSpacing的当前值替换minimumInteritemSpacing
):
flowLayout.itemSize = CGSizeMake((_collectionView.frame.size.width/3.0)-(flowLayout.minimumInteritemSpacing/3.0), _collectionView.frame.size.height);
我将此计算放在viewDidLayoutSubviews
中,并且它在某些屏幕上无法正常工作,因为它们的当前interItemSpacing
与minimumInteritemSpacing
不同
提前感谢。
答案 0 :(得分: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)
}
答案 1 :(得分: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/