简体   繁体   中英

How to make UICollectionview cell height dynamic?

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.

How to do that?

1-Add UICollectionViewDelegateFlowLayout protocol
2-Conform to protocol by implement the sizeForItemAtIndexPath method in your ViewController
3-By the index of the cell get the text you have and caculate the hight 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)
}

}

Use NSAttributedString in sizeForItemAtIndexPath to calculate rect for the height and width:

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) Override collectionflowlayout delegate method

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

2) In above method, Calculate the height of textview which contains dynamic length and add that value in your fixed height. Ex. cellHeight = 100 + textview height. //100 is height which not contain textview height.

3) After calculating height, replace it in above method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM