How to make UICollectionview cell height dynamic?

江枫思渺然 提交于 2020-01-03 18:14:30

问题


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:


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

}



回答2:


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:


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


来源:https://stackoverflow.com/questions/38759138/how-to-make-uicollectionview-cell-height-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!