如何使 UICollectionview 单元格高度动态化? [英] How to make UICollectionview cell height dynamic?

查看:24
本文介绍了如何使 UICollectionview 单元格高度动态化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UIcollectionview.Collectionview 有一些单元格.在那个 CollectionviewCell 里面有一个 textview.textview 的内容是动态的.所以单元格高度应该是动态的.

I have a UIcollectionview. There are some cells of the Collectionview. Inside that CollectionviewCell there is a textview. The textview's content is dynamic. So the cell height should be dynamic.

怎么做?

推荐答案

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

1-Add UICollectionViewDelegateFlowLayout protocol.
2-Conform to protocol by implement the sizeForItemAtIndexPath method in your ViewController.
3-Use the index of the cell to get the text you have and calculate the height and width of it.

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

}

这篇关于如何使 UICollectionview 单元格高度动态化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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