【发布时间】:2017-03-25 00:45:25
【问题描述】:
我有以下布局
- UITableView
- UITableViewCell(类:CategoryCell)
- 标签
- 按钮
- UICollectionView
- UICollectionViewCell(类:ItemCell)
- UIImageView
- UILabel
- UICollectionViewCell(类:ItemCell)
- UITableViewCell(类:CategoryCell)
我正在尝试让 UICollectionView 始终显示 3 个项目,无论屏幕大小如何。我能够根据屏幕宽度显示要显示的项目,并且能够设置高度。但是,表格视图的高度不会从 CategoryCell 内部改变。代码如下:
// 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)
【问题讨论】:
标签: ios swift uitableview uicollectionview