How to make UICollectionview cell height dynamic?

2019-06-27 11:06发布

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?

3条回答
甜甜的少女心
2楼-- · 2019-06-27 11:32

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

}
查看更多
对你真心纯属浪费
3楼-- · 2019-06-27 11:39

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

}
查看更多
【Aperson】
4楼-- · 2019-06-27 11:46

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)
    }
查看更多
登录 后发表回答