CollectionView Dynamic cell height swift

前端 未结 3 1819
傲寒
傲寒 2020-12-08 19:37

Im trying to create a collection view with cells displaying string with variable length.

Im using this function to set cell layout:

 func collectionV         


        
3条回答
  •  情深已故
    2020-12-08 19:57

    While the answer above may solve your problem, it establishes a pretty crude way of assigning each cells height. You are being forced to hard code each cell height based on some estimation. A better way of handling this issue is by setting the height of each cell in the collectionview's sizeForItemAtIndexPath delegate method.

    I will walk you through the steps on how to do this below.

    Step 1: Make your class extend UICollectionViewDelegateFlowLayout

    Step 2: Create a function to estimate the size of your text: This method will return a height value that will fit your string!

    private func estimateFrameForText(text: String) -> CGRect {
        //we make the height arbitrarily large so we don't undershoot height in calculation
        let height: CGFloat = 
    
        let size = CGSize(width: yourDesiredWidth, height: height)
        let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]
    
        return NSString(string: text).boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
    }
    

    Step 3: Use or override delegate method below:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        var height: CGFloat = 
    
       //we are just measuring height so we add a padding constant to give the label some room to breathe! 
        var padding: CGFloat = 
    
        //estimate each cell's height
        if let text = array?[indexPath.item].text {
             height = estimateFrameForText(text).height + padding
        }
        return CGSize(width: yourDesiredWidth, height: height)
    }
    

提交回复
热议问题