Search code examples
iosswiftuicollectionviewuicollectionviewcelldynamic-sizing

Dynamic collection view cell resizing not working correctly


I was trying to create UICollectionView with dynamic cell sizing and this cell contains an imageView and a label and It works fine but can't set the number of items per row and the row contains only 1 item and I need the number of items per row changing dependent on items' sizes:

ViewController code:

   import UIKit
    
    class ViewController: UIViewController {
    //MARK: - Outlets
        
        @IBOutlet weak var collectionViewOutlet: UICollectionView!
        @IBOutlet weak var collectionLayout: UICollectionViewFlowLayout! {
            didSet {
                   collectionLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
               }
        }
        //MARK: - Vars
        let items: [Item] = [Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "1.jpg")!), Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "2.jpg")!), Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "3.jpg")!),Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "2.jpg")!), Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "1.jpg")!), Item(title: "abscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjascabscancnakcnaslcnajcacnajkcnajncajsncjasc", image: UIImage(named: "3.jpg")!)]
     
 

     //MARK: - Insets
        let itemsPerRow = 2

let sectionInsets = UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)

        
        //MARK: - Life Cycle
        override func viewDidLoad() {
            super.viewDidLoad()
            collectionViewOutlet.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
        }
    
    
    }
    
    extension ViewController:UICollectionViewDelegate, UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return items.count
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionViewOutlet.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
            cell.imageOutlet.image = items[indexPath.item].image
            cell.lblTitleOutlet.text = items[indexPath.item].title
            cell.imageMaxWidth = collectionViewOutlet.bounds.width - 5
            cell.lblMaxWidth = collectionViewOutlet.bounds.width - 5
    
            
            return cell
        }
        
        
        }

    //MARK: - Collection View Flowlayout
    extension ViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            let paddingSpace = Int(sectionInsets.left) * (itemsPerRow + 1)
            let availableWidth = Double (view.frame.width) - Double(paddingSpace)
            let WidthForItem = availableWidth / Double(itemsPerRow)
            return CGSize(width: WidthForItem - 5 , height: WidthForItem - 5 )
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
            
            return sectionInsets
        }
        
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
            
            return sectionInsets.left
        }
    }

CollectionViewCell code:

import UIKit

class CollectionViewCell: UICollectionViewCell {
//MARK: - Outlets
    
    @IBOutlet weak var imageOutlet: UIImageView!
    
    @IBOutlet weak var lblTitleOutlet: UILabel!
    @IBOutlet private var imageMaxWidthConstraint: NSLayoutConstraint! {
         didSet {
             imageMaxWidthConstraint.isActive = false
         }
     }
    
    @IBOutlet private var lblMaxWidthConstraint: NSLayoutConstraint! {
         didSet {
            lblMaxWidthConstraint.isActive = false
         }
     }
     
     var imageMaxWidth: CGFloat? = nil {
         didSet {
             guard let maxWidth = imageMaxWidth else {
                 return
             }
             imageMaxWidthConstraint.isActive = true
             imageMaxWidthConstraint.constant = maxWidth
         }
     }
   
     
     var lblMaxWidth: CGFloat? = nil {
         didSet {
             guard let maxWidth = lblMaxWidth else {
                 return
             }
            lblMaxWidthConstraint.isActive = true
            lblMaxWidthConstraint.constant = maxWidth
         }
     }
    //MARK: - Awake
    override func awakeFromNib() {
        super.awakeFromNib()
        contentView.translatesAutoresizingMaskIntoConstraints = false
             
             NSLayoutConstraint.activate([
                 contentView.leftAnchor.constraint(equalTo: leftAnchor),
                 contentView.rightAnchor.constraint(equalTo: rightAnchor),
                 contentView.topAnchor.constraint(equalTo: topAnchor),
                 contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
             ])
    }

}

Item code:

import Foundation
import UIKit

struct Item {
    var title: String?
    var image : UIImage
    init(title: String, image: UIImage) {
        self.title = title
        self.image = image
    }
}

Output 1: If collectionLayout connected:

enter image description here

Output 2: If collectionLayout not connected I will have the output I need but images can't appear:

enter image description here

I need output 2 but with all the images in my array, any help will be appreciated...


Solution

  • Fix 1 : How to get Output 2 with outlet connected?
    @IBOutlet weak var collectionLayout: UICollectionViewFlowLayout! {
        didSet {
            // Stop doing this
            /*
            collectionLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
            */
        }
    }
    
    Fix 2 : How to make sure images are always shown regardless of how long the text is?
    1. Set a minimum height >= 60/or whatever image size you want with maximum text size constraint for your UIImageView instance in the cell.

    OR

    1. Set proportional height constraints to superview for both. 0.7 for UIImageView / 0.3 for UILabel.

    OR

    1. Limit the max number of lines for UILabel say to 3/5 etc.