2017-07-25 70 views
0

我需要确定uicollectionview的高度。如何在swift中统计uicollectionview的行数

let layout = contactCollectionView.collectionViewLayout 
let heightSize = String(Int(layout.collectionViewContentSize.height)) 

上述解决方案适用于我的项目中的一些情况。在这种特定的情况下,我需要对行数进行计数,然后将其与一个数字相乘以找到高度。

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
     // height = (count rows) * 30 . every cell height is 30 
     // every cell has different width. 
     return (presenter?.selectedContact.count)! 
    } 

如何查找行数?

更新

看图像。 enter image description here

这是我的收藏查看。每个单元格都有不同的宽度(因为它是字符串)。所以它有不同的行。这个的CollectionView的宽度view.frame

+0

你的意思是你要查找的滚动高度?像整个内容的大小? – LinusGeffarth

+0

layout.collectionViewContentSize.height在这种情况下返回零。因为我的stackView的高度为零,并且无法计算高度。我需要计算数字行数,然后用数字计算多个数字以查找整个内容大小。 –

+0

所以你想知道返回30后它会*的高度,对吧? – LinusGeffarth

回答

1

如果collectionViewwidth比以前的总宽(s),那么您可以通过一个递增rowCounts更大您可以比较的宽度。我假设你正在实施UICollectionViewDelegateFlowLayout方法,并且每个细胞你现在知道动态width。如果您当时不知道宽度,则还可以计算stringwidth,该值将考虑UIfont以及每个单元中的其他内容。

这里是一个参考如何计算stringhttps://stackoverflow.com/a/30450559/6106583

东西的width像下面

//stored properties 
var totalWidthPerRow = CGFloat(0) 
var rowCounts = 0 
let spaceBetweenCell = CGFloat(10) // whatever the space between each cell is 


func collectionView(_collectionView:UICollectionView,layoutcollectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize { 

    let collectionViewWidth = view.frame.width 
    let dynamicCellWidth = //whatever you calculate the width 
    totalWidthPerRow += dynamicCellWidth + spaceBetweenCell 


    if (totalWidthPerRow > collectionViewWidth) { 
     rowCounts += 1 
     totalWidthPerRow = dynamicCellWidth + spaceBetweenCell 
    } 

    return CGSizeMake(dynamicCellWidth , CGFloat(30)) 
} 
相关问题