I have the following layout
- UITableView
- UITableViewCell (class: CategoryCell)
- Label
- Button
- UICollectionView
- UICollectionViewCell (class: ItemCell)
- UIImageView
- UILabel
- UICollectionViewCell (class: ItemCell)
- UITableViewCell (class: CategoryCell)
I am trying to make UICollectionView to always show 3 items no matter the screen size. I was able to get items to be shown based on screen width and was able to set the height. However, the height of table view does not change from inside CategoryCell. Here is the code:
// CategoryCell.swift
func awakeFromNib() {
super.awakeFromNib()
// Calculate width and height based on screen width
let screenWidth = UIScreen.main.bounds.width
let itemWidth = screenWidth / 3.0
let itemHeight = itemWidth / 0.75 // 3:4 aspect ratio
// Change height of table view cell
self.bounds.size.height = self.bounds.size.height - collectionView.bounds.size.height + itemHeight
// This is the line does nothing
// It should remove collectionView height from tableView (height of collectionView is set through autolayout) then add he new height to it.
// Set collection view height to equal to item height
collectionView.bounds.size.height = itemHeight
// set item height
let layout = collectionViewProducts.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: itemWidth, height: itemHeight - 1.0)
// -1.0 because item/cell height needs to be SMALLER than collection view height
}
How can I change table view cell height from inside the cell class itself? My only guess is that I should not be doing these operations inside awakeFromNib but I am not able to find another function to call these from.
EDIT: I am using RxSwift, so my data source code is the following:
let observable = Observable.just(data)
observable.bindTo(tableView.rx.items(cellIdentifier: "CategoryCell", cellType: CategoryCell.self)) { (row, element, cell) in
cell.setCategory(category: element)
}.disposed(by: disposeBag)
tableView.rx.setDelegate(self).disposed(by: disposeBag)