0

I have decided start a project with no storyboard for the first time and at the moment I am stuck trying to figuring out how to achieve a proper dynamic cell in my CollectionViewController. Reading some of the solutions here in Stackoverflow I got the point in using a layout.estimatedItemSize but it somehow stops the bouncing effect from the collection view and also in my second cell which is a horizontal scroll view will not work after this implementation.

Here is my code(UICollectionViewController):

class InfoEmpaVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    
fileprivate let cell1 = "cell1"
fileprivate let cell2 = "cell2"

fileprivate let cellID = "cellID"
fileprivate let headerID = "headerID"
fileprivate let padding: CGFloat = 10

//


//
    
//GET THE DATA FROM:
var empanada: Empanadas!

struct Cells {
    static let empanadaStepsCell = "EmpanadaStepsCell"
}


override func viewDidLoad() {
    super.viewDidLoad()
    
    
    
    setupCollectionViewLayout()
    setupCollectionView()
    
    
}



//CHANGE COLOR OF STATUS BAR
override var preferredStatusBarStyle: UIStatusBarStyle {
    return .lightContent
}

fileprivate func setupCollectionView() {
    
    collectionView.backgroundColor = UIColor(named: "ColorBackground")
    collectionView.contentInsetAdjustmentBehavior = .never
    
    
    collectionView.delegate = self
    collectionView.dataSource = self
    
    collectionView.register(InfoHeaderVC.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerID)
    
    
    //FirstCELL
    collectionView.register(EmpaIngredientsListCell.self, forCellWithReuseIdentifier: cell1)
    //SecondCELL
    collectionView.register(EmpaStepsCell.self, forCellWithReuseIdentifier: cellID)
    

}

fileprivate func setupCollectionViewLayout() {
    if let layout = collectionViewLayout as? UICollectionViewFlowLayout {

        layout.sectionInset = .init(top: padding, left: padding, bottom: padding, right: padding)
        layout.estimatedItemSize = CGSize(width: view.frame.width, height: 50)
    }
}


var headerView: InfoHeaderVC!

//HEADER COLLECTION VIEW
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    
    headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerID, for: indexPath) as? InfoHeaderVC
    
    headerView.empaImageView.image = UIImage(named: empanada.image)
    headerView.empaTitleLabel.text = empanada.name
    headerView.empaDescriptionLabel.text = empanada.info
    headerView.buttonX.addTarget(self, action: #selector(dismissVC), for: .touchUpInside)
    headerView.buttonAddFavorite.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside)
    
    
    
    return headerView!
}
    

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return .init(width: view.frame.width, height: 350)
    
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
   return 2
    
}


override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    if indexPath.item == 0 {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cell1, for: indexPath)
        
        guard let cellOne = cell as? EmpaIngredientsListCell else {
            fatalError("Wrong cell type for section 0. Expected CellTypeOne")
        }
        
        //INGREDIENT LIST
        
        cellOne.empaIngredientList.ingredientList.append(contentsOf: empanada.ingredients)
        cellOne.empaIngredientList.configure()
        
        return cellOne
        
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! EmpaStepsCell
        
        
        cell.pasos.append(contentsOf: empanada.pasos)
        cell.titleHeaderLabel.text = "Step by Step"
        cell.configure()
        
        print (cell.pasos.count)
        
        return cell
    }
}





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

    if indexPath.item == 0 {


        return .init(width: view.frame.width - 2 * padding, height: 300)


    } else {
        return .init(width: view.frame.width - 2 * padding, height: 300)
    }


}



//OBJC FUNC
@objc func dismissVC() {
    dismiss(animated: true)
}

//SAVE DATA
@objc func addButtonTapped() {
    configureSaveToFavorites(empanada: empanada!)
    
}

}

Cell 1:

import UIKit import SnapKit class EmpaIngredientsListCell: UICollectionViewCell {

let empaIngredientList = EmpaIngredientsContainerView()


override init(frame: CGRect) {
    super.init(frame: frame)
    
    setupUI()
    
    print(intrinsicContentSize)
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}



override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    setNeedsLayout()
    layoutIfNeeded()
    let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)

    var frame = layoutAttributes.frame
    frame.size.height = ceil(size.height)

    layoutAttributes.frame = frame



    return layoutAttributes
}


func setupUI() {
    
    //contentView.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(empaIngredientList)

    
    empaIngredientList.snp.makeConstraints { (make) in

        make.top.bottom.left.right.equalTo(self.contentView)
        make.edges.equalTo(self.safeAreaLayoutGuide)
      
    }
}

}

Miguel P.
  • 17
  • 8
  • 1
    I would highly encourage you to look into Compositional Layouts as it's super easy and powerful: https://medium.com/better-programming/ios-13-compositional-layouts-in-collectionview-90a574b410b8 – gmogames Jan 22 '21 at 23:19
  • 1
    @gmogames Thanks after banging my head many times I finally sorted out changing to Compositional Layouts. – Miguel P. Jan 25 '21 at 13:34

0 Answers0