【发布时间】:2015-06-22 03:04:19
【问题描述】:
我觉得这应该比现在容易得多。我想要做的就是为我的每个集合视图的单元格设置不同的高度(取决于每个单元格内标签的大小)。我正在使用sizeForItemAtIndexPath,但问题是在创建单元格之前确定高度。
我现在拥有的:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
// target width of each cell - widht of the collectionView
let targetWidth: CGFloat = collectionView.frame.width - 20.0
// setup a prototype cell
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCustomCellIdentifier", forIndexPath: indexPath) as! MyCustomCell
// for the sake of simplicity, let's just assume data is coming from somewhere else
cell.nameLabel.text = data.name
cell.notesLabel.text = data.notes
// resize - layoutSubviews in LocationCell controller
cell.layoutIfNeeded()
// get the size based on constraints
var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
// force width
size.width = targetWidth
return size
}
不工作的是dequeueReusableCellWithReuseIdentifier。我猜这是因为UICollectionViewCell 还不可用?我也试过registerClass 来得到它,但这似乎也不起作用。 :(
有没有更简单的方法可以完全做到这一点?我需要做的就是在创建单元格之前弄清楚它的高度。我需要UICollectionViewCell 子类的实例才能启动(这样我实际上可以访问标签并尝试确定高度)。被困在这几个小时了。 :/
【问题讨论】: