Neelam Pursnani
Neelam Pursnani

Reputation: 246

Dynamic height for UICollectionViewCell

I want dynamic cell Size as per text in TextView, Here is my code

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
        {
            return DataArray.count
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
        {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CustomCollectionViewCell

            let fixedWidth = cell?.TextView.frame.size.width
            cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude))
            let newSize = cell?.TextView.sizeThatFits(CGSize(width: fixedWidth!, height: CGFloat.greatestFiniteMagnitude))
            var newFrame = cell?.TextView.frame
            newFrame?.size = CGSize(width: max((newSize?.width)!, fixedWidth!), height: (newSize?.height)!)
            cell?.TextView.frame = newFrame!
            TextViewFrame = newFrame!
            cell?.TextView.text = DataArray[indexPath.row] as? String
            return cell!
        }
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
        {

            return CGSize(width: CV.frame.size.width, height: 200)
        }

Here i have given 200 fixed size for cell. it gives me output as below It gives me cell height 200 for small content as well as for large content . But actually i want cell height as per content. How can i achieve this? Any help is appreciated. Thanks in advance enter image description here

Upvotes: 1

Views: 1969

Answers (1)

Adeel Miraj
Adeel Miraj

Reputation: 2496

You can find the height of the cell once you know the bounding rect for the text you want to display.

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let text = "String that you want to show in the label inside the cell"
    let boundingRect = NSString(string: text).boundingRectWithSize(CGSizeMake(collectionView.bounds.width, 1000),
                                                                   options: .UsesLineFragmentOrigin,
                                                                   attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)],
                                                                   context: nil)

    let size = CGSizeMake(collectionView.bounds.width, ceil(boundingRect.height))

    return size
}

Just be sure to make up for the top/bottom/left/right margins of your label to the cell.

Upvotes: 1

Related Questions