Search code examples
iosswiftuicollectionviewxcode10ios12

How to properly add an UICollectionView inside UITableViewCell using IOS 12


For some reasons I cannot properly display some items from a collection inside an tableview cell when using Xcode 10 beta. I tried all I know for the last 4 days.

I made a small project sample to see what my issue is.
Full code is here if someone wants to run it locally: https://github.com/adrianstanciu24/CollectionViewInsideUITableViewCell

I first add an table view with 2 different resizable cells, first cell has the collection view and a label:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 44
        tableView.rowHeight = UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "collCell") as! CollectionTableViewCell
            cell.collectionView.collectionViewLayout.invalidateLayout()

            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "normalCell")!

            return cell
        }
    }
}

Here is the cell with collection view defined. This also has a height constraint which I updated in layoutSubviews:

class CollectionTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!


    override func awakeFromNib() {
        super.awakeFromNib()

        collectionView.delegate = self
        collectionView.dataSource = self

        if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        collectionViewHeightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize.height
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "taskCell", for: indexPath as IndexPath) as! TaskCollectionViewCell

        cell.name.text = "Task_" + String(indexPath.row)

        return cell
    }
}

Below is a screenshot with the collection view constraint and how the storyboard looks:

enter image description here

And this is how it looks when running:

enter image description here

The cells are squashed and label on top disappears. What I want is the collection view should grow to show all elements and also making table view cell to resize, but that is not happening at the moment and I can't figure out where the issue is.


Solution

  • If you want the following output:

    enter image description here

    Code ViewController:

    class ViewController: UIViewController {
        let list = [String](repeating: "Label", count: 10)
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addSubview(tableView)
            tableView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
                tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
                tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
                ])
            tableView.reloadData()
        }
    
        public lazy var tableView: UITableView = { [unowned self] in
            let v = UITableView.init(frame: .zero)
            v.delegate = self
            v.dataSource = self
            v.estimatedRowHeight = 44
            v.rowHeight = UITableViewAutomaticDimension
            v.register(TableCell.self, forCellReuseIdentifier: "TableCell")
            return v
        }()
    }
    extension ViewController: UITableViewDelegate{
    
    }
    extension ViewController: UITableViewDataSource{
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return list.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! TableCell
            cell.label.text = "\(list[indexPath.row]) \(indexPath.row)"
            return cell
        }
    }
    

    TableCell:

    class TableCell: UITableViewCell{
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            commonInit()
        }
    
        func commonInit(){
            contentView.addSubview(label)
            contentView.addSubview(collectionView)
            updateConstraints()
        }
    
        override func updateConstraints() {
            label.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                label.topAnchor.constraint(equalTo: topAnchor),
                label.leadingAnchor.constraint(equalTo: leadingAnchor),
                label.trailingAnchor.constraint(equalTo: trailingAnchor)
                ])
            collectionView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                collectionView.topAnchor.constraint(equalTo: label.bottomAnchor),
                collectionView.leadingAnchor.constraint(equalTo: leadingAnchor),
                collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
                collectionView.trailingAnchor.constraint(equalTo: trailingAnchor),
                ])
            super.updateConstraints()
        }
    
        let list = [String](repeating: "Task_", count: 10)
        public let label: UILabel = {
            let v = UILabel()
            v.textAlignment = .center
            return v
        }()
    
        public lazy var collectionView: UICollectionView = { [unowned self] in
            let layout = UICollectionViewFlowLayout()
            layout.minimumLineSpacing = 0
            layout.minimumInteritemSpacing = 0
            let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
            v.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
            v.delegate = self
            v.dataSource = self
            v.isScrollEnabled = false
            return v
        }()
    
        override func sizeThatFits(_ size: CGSize) -> CGSize {
            let collectionCellHeight = 50
            let rows = list.count / 5 // 5: items per row
            let labelHeight = 20 // you can calculate String height
            let height = CGFloat((collectionCellHeight * rows) + labelHeight)
            let width = contentView.frame.size.width
            return CGSize(width: width, height: height)
        }
    }
    extension TableCell: UICollectionViewDataSource{
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return list.count
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
            cell.label.text = "\(list[indexPath.item])\(indexPath.item)"
            return cell
        }
    }
    extension TableCell: UICollectionViewDelegate{
    
    }
    extension TableCell: UICollectionViewDelegateFlowLayout{
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: collectionView.frame.width/5, height: 50)
        }
    }
    

    CollectionCell

    class CollectionCell: UICollectionViewCell{
        let padding: CGFloat = 5
        override init(frame: CGRect) {
            super.init(frame: frame)
            commonInit()
        }
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    
        func commonInit(){
            backgroundColor = .yellow
            contentView.addSubview(label)
            updateConstraints()
        }
    
        override func updateConstraints() {
            label.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
               label.topAnchor.constraint(equalTo: topAnchor, constant: padding),
                label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding),
                label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding),
                label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -padding)
                ])
            super.updateConstraints()
        }
    
        public let label: UILabel = {
            let v = UILabel()
            v.textColor = .darkText
            v.minimumScaleFactor = 0.5
            v.numberOfLines = 1
            return v
        }()
    }