0

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.

  • 1
    Calculate the width of the UILabel: https://stackoverflow.com/questions/3527494/how-to-calculate-uilabel-width-based-on-text-length And then implement func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize of UICollectionViewDelegateFlowLayout – DungeonDev Nov 28 '18 at 13:55

2 Answers2

1

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)
}
Sateesh Yemireddi
  • 4,289
  • 1
  • 20
  • 37
0

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

Pratyush Pratik
  • 683
  • 7
  • 14