如何使UICollectionView细胞高度dynamic?

我有一个UIcollectionview 。 有一些CollectionView的单元格。 在那个CollectionviewCell里面有一个textview。 textview的内容是dynamic的。 所以细胞高度应该是dynamic的。

怎么做?

1 – 添加UICollectionViewDelegateFlowLayout协议
2-通过在您的ViewController中实现sizeForItemAtIndexPath方法来符合协议
3 – 通过单元格的索引获取文本,并计算它的高度和宽度

 class ViewController: UIViewController,UICollectionViewDelegateFlowLayout{ func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let constraintRect = CGSize(width: self.view.frame.size.width, height: CGFloat.max) let data = myTextArray[indexpath.row]; let boundingBox = data.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: Constants.strings.fontName, size: 30)!], context: nil) return CGSizeMake(boundingBox.width, boundingBox.height); //(width,hight) } } 

sizeForItemAtIndexPath使用NSAttributedString来计算高度和宽度的rect:

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let attString = NSAttributedString(string: self.rows[indexPath.row], attributes: [NSFontAttributeName: UIFont.systemFontOfSize(15.0)]) var r: CGRect = attString.boundingRectWithSize(CGSizeMake(self.collectionView.bounds.size.width, CGFLOAT_MAX), options: .UsesLineFragmentOrigin, context: nil) return r.size } 

1)覆盖collectionflowlayout委托方法

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(50, 50); //(width,hight) } 

2)在上面的方法中,计算包含dynamic长度的textview的高度,并将该值添加到您的固定高度。 Ex. cellHeight = 100 + textview height. //100 is height which not contain textview height.

3)计算高度后,按上述方法更换

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(50, dynamicheight); //(width,hight) } 

在目标-c

  - (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath { if ()//your condition { return 280; } else { return 330; } } 

迅速

 func collectionView(collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize { //check your conditions here ex: device, iOS version then return return CGSizeMake(64, 64) }