[英]How to make UICollectionview cell height dynamic?
我有一个UIcollectionview
。 Collectionview有一些单元格。 在CollectionviewCell
里面有一个textview。 textview的内容是动态的。 因此,细胞高度应该是动态的。
怎么做?
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)在上述方法中,计算包含动态长度的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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.