2016-04-13 6 views
0

как я могу получить фактический interItemSpacing для горизонтальной раскладки потока в UICollectionView? единственная информация, которую я могу получить (и установить), - minimumInteritemSpacing.получить фактическое расстояние между элементами UICollectionView

мне это нужно ради следующего небольшого расчета всегда отображать 3 одинаково шириной элементов в представлении коллекции, независимо от размера экрана (я хочу, чтобы заменить minimumInteritemSpacing с текущим значением interItemSpacing в формуле): flowLayout.itemSize = CGSizeMake((_collectionView.frame.size.width/3.0)-(flowLayout.minimumInteritemSpacing/3.0), _collectionView.frame.size.height); I поместите этот расчет в viewDidLayoutSubviews, и он не работает точно для некоторых экранов, потому что их ток interItemSpacing отличается от minimumInteritemSpacing

заранее.

ответ

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/