0

size collection view cells like below and it should be capable of adapt the same design throughout the cells in any count of JSON response.

I need something like this

I did this from button shape but it only contains 4 static items.

But I need to adapt same style of collection view cell for following UI.

extension CategoryVC: UICollectionViewDelegate, UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.categories.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CatCell", for: indexPath) as! CatCell
    DispatchQueue.main.async {
          cell.configureCell()  

        cell.imageView.layer.cornerRadius = 5
        cell.grImageView.layer.cornerRadius = 5
        cell.imageView.image = self.ItemImageArray[indexPath.row]

        let category = self.categories[indexPath.row]
        cell.itemImageName.text = category.name ?? ""
    }
    return cell
}

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

        return CGSize(width: 173.0, height: 173.0)
    }
}

I tried several experiments by using sizeForItemAt delegate method but not getting the desired results.

I went through so many StackOverflow posts and web results still not got the suited code snippets for my question.

Please help me. Thanks in Advance

Fido
  • 218
  • 1
  • 17

2 Answers2

1

Your cells should override preferredLayoutAttributesFittingAttributes and return the size they need for their content.

You need to do some basic aspect ratio math here. The layout attributes will give you the width. Since you need to have variable height based on your content size, calculate your content.width / content.height and return a size with width: layout.width and height: layout.width * content height / content.width.

https://developer.apple.com/documentation/uikit/uicollectionreusableview/1620132-preferredlayoutattributesfitting?language=objc

Josh Homann
  • 15,933
  • 3
  • 30
  • 33
0

Thanks for support guys, actually I managed to do this from the reference of this tutorial This link now my collectionView is looking like this enter image description here

Fido
  • 218
  • 1
  • 17