我正在尝试根据其中包含的标签文本的长度调整每个 Collection View 单元格的大小
func collectionView(collectionView: UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size = CGSize()
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("lessonCell", forIndexPath: indexPath) as UICollectionViewCell
var label: UILabel = cell.viewWithTag(300) as UILabel
var labelSize = label.frame.size
size = labelSize
return size
}
运行代码时,应用程序崩溃并出现错误“流式布局不支持负尺寸或零尺寸。”但是,当我逐步执行时,我发现崩溃发生在初始化单元格变量时,甚至在确定大小之前。为什么初始化我的单元格变量会引发此类错误?
最佳答案
我发现了我的问题。我使用的是 collectionView.dequeueReusableCellWithReuseIdentifier(),而实际上这应该只与“cellForItemAtIndexPath”委托(delegate)方法一起使用。对我有用的是以下代码:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var size = CGSize(width: 0, height: 0)
var label = UILabel()
label.text = category[indexPath.row]
label.sizeToFit()
var width = label.frame.width
size = CGSize(width: (width+20), height: 50)
return size
}
关于ios - 在 Swift 中调整 UICollectionViewCell 的大小时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744882/