[英]Change UICollectionViewCell height to fit UILabel
I am trying to make my cell height size fit with label. 我想让我的细胞高度大小与标签一致。 The thing is that the label text is set in the
cellForItemAtIndexPath
, and if i have understood correct, sizeForItemAtIndexPath
runs before the cellForItemAtIndexPath
. 问题是标签文本在
cellForItemAtIndexPath
设置,如果我理解正确, sizeForItemAtIndexPath
在cellForItemAtIndexPath
之前运行。 This is something i have tried so far: 这是我到目前为止尝试过的事情:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let imageCell = collectionView.dequeueReusableCellWithReuseIdentifier("imageCell", forIndexPath: indexPath) as? CollectionViewCell
imageCell!.imageText.text = post.text // This set the UICollectionView Cell text
imageCell!.frame.size.height = (imageCell!.frame.size.height) + (imageCell!.imageText.frame.size.height)
return imageCell!
}
I am not using Auto Layout. 我没有使用自动布局。
Any suggestions why the cell height not changes depending on the label? 任何建议为什么细胞高度不会根据标签变化?
This used to be an annoying problem to solve, but it gets substantially easier if you're able to use Auto Layout. 这曾经是一个令人烦恼的问题需要解决,但如果你能够使用自动布局,它会变得非常容易。 See this answer for a thorough walkthrough.
请参阅此答案以获得详尽的演练。
Even if sizeForItemAtIndexPath
runs first, that's the place to set the size of the cell. 即使
sizeForItemAtIndexPath
首先运行,也就是设置单元格大小的地方。 cellForItemAtIndexPath
cannot change the size. cellForItemAtIndexPath
无法更改大小。
In sizeForItemAtIndexPath
you need to find out the image size for each cell, then return that size. 在
sizeForItemAtIndexPath
您需要找出每个单元格的图像大小,然后返回该大小。
Something like this: 像这样的东西:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let imageCell = collectionView.cellForItemAtIndexPath(indexPath) as! CollectionViewCell
let size = CGSize(width: imageCell.frame.width, height: imageCell.frame.size.height + imageCell.imageText.frame.size.height)
return size
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.