如何使UICollectionview单元格高度动态?

时间:2016-08-04 05:32:10

标签: ios swift uicollectionview uicollectionviewcell

我有UIcollectionview。 Collectionview有一些单元格。在CollectionviewCell里面有一个textview。 textview的内容是动态的。因此,细胞高度应该是动态的。

怎么做?

3 个答案:

答案 0 :(得分:3)

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

}

答案 1 :(得分:2)

sizeForItemAtIndexPath中使用NSAttributedString计算高度和宽度的矩形:

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

}

答案 2 :(得分:0)

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)
    }
相关问题