Shivam Srivastava
Shivam Srivastava

Reputation: 189

How to make UICollectioncell width dynamic according to text

Guys I want to change the size of the cell like this enter image description here

Auto adjusting to the text. what I am able to achieve is enter image description here

I have tried to search but not able to find out the solution. How can I make it dynamic to text. The tags are coming from a model class and the colour and background is changing from custom class for the cell.

Upvotes: 0

Views: 663

Answers (2)

Sateesh Yemireddi
Sateesh Yemireddi

Reputation: 4409

Its explained in the answer below.

HorizontalCollectionView Content width and spacing

Calculate size of string with associate font.

extension String {
    func size(with font: UIFont) -> CGSize {
        let fontAttribute = [NSAttributedString.Key.font: font]
        let size = self.size(withAttributes: fontAttribute)
        return size
    }
}

Return the calculated width along with collectionView height in collectionView(_, collectionViewLayout:_, sizeForItemAt).

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let newWidth = titles[indexPath.row].size(with: labelFont!).width + 10 //Added 10 to make the label visibility very clear
    return CGSize(width: newWidth, height: collectionView.bounds.height)
}

Upvotes: 1

Pratyush Pratik Sinha
Pratyush Pratik Sinha

Reputation: 714

Check the code below:-

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let btn = UIButton()
        btn.setTitle(?*self.arr[indexPath.row].name, for: .normal)
        let btnWidth =  ?*btn.intrinsicContentSize.width > UIScreen.main.bounds.width - 32 ? ?*btn.intrinsicContentSize.width - 32 : ?*btn.intrinsicContentSize.width
        return CGSize(width: (?*btnWidth), height: 48)
    }

You can modify it according to your requirement. Comment if you need any help in this.

Hope it helps :)

Upvotes: 0

Related Questions