我有以下布局
- UITableView
- UITableViewCell (类别单元格)
- 标签
- 按钮
- UICollectionView
- UICollectionViewCell (物品单元格)
- UIImageView
- UILabel
- UICollectionViewCell (物品单元格)
- UITableViewCell (类别单元格)
我试图使UICollectionView始终显示3个项目,无论屏幕大小如何。我能够根据屏幕宽度显示项目,并设置高度。然而,来自CategoryCell内部的TableView的高度没有改变。以下是代码:
// 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
}
如何在单元格类内部更改表格视图单元格高度? 我唯一的猜测是,我不应该在awakeFromNib中执行这些操作,但我找不到另一个函数来调用这些操作。
编辑:我正在使用RxSwift,因此我的数据源代码如下:
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)