2017-07-25 33 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)) 
}