如何快速计算uicollectionview的行数 [英] How to count number of uicollectionview's rows in swift

查看:151
本文介绍了如何快速计算uicollectionview的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定 uicollectionview 的高度.

I need to determine uicollectionview's height.

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

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

The above solution works on some situations in my project. In this specific situation I need to count number of rows and then multiple it with a number to find 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)!
    }

如何找到行数?

更新

看图.

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

This is my collectionView. Every cell has different width(because it is string). So It has different rows. The width of this collectionView is width of view.frame

推荐答案

你可以比较 collectionViewwidth 是否大于之前的总宽度您将 rowCounts 加一.我假设您正在实施 UICollectionViewDelegateFlowLayout 方法,并且您现在知道每个单元格的动态 width.如果你不知道那个时候的宽度,你也可以计算 stringwidth ,考虑 UIfont 和其他每个单元格中的东西.

You can compare if the collectionView's width is greater than total previous width(s) then you increment rowCounts by one. I am assuming you are implementing UICollectionViewDelegateFlowLayout methods and per each cell you know the dynamic width at the moment. if you won't know the width at that moment, you can also calculate the width of string that would take with considering UIfont along with other stuff in each cell.

这是如何计算 stringwidth https 的参考://stackoverflow.com/a/30450559/6106583

Here is a reference how to calculate the width of a string https://stackoverflow.com/a/30450559/6106583

类似于下面的内容

//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))
}
    
   

这篇关于如何快速计算uicollectionview的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆