【问题标题】:iOS8/Swift: UICollectionViewCell height calculationiOS8/Swift:UICollectionViewCell 高度计算
【发布时间】:2026-02-19 02:30:01
【问题描述】:

从有关该主题的其他帖子中得出,我尝试了以下方法-但不知何故,“foo”和“bar”似乎为零

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewFlowLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    var foo = collectionView.cellForItemAtIndexPath(indexPath) as? messageCell

    var bar = foo?.messageText.frame.height

    return CGSizeMake(self.view.frame.width-20, bar!+20)

}

自定义单元格的类:

class messageCell: UICollectionViewCell,UIPopoverPresentationControllerDelegate,UITextViewDelegate{


@IBOutlet weak var authorLabel: UILabel!

@IBOutlet weak var timestampLabel: UILabel!

@IBOutlet weak var messageText: UITextView!



func setCell(authorLabelText:String, messageText:String,timestampLabelText:String) {

    self.authorLabel?.text = authorLabelText
    self.timestampLabel?.text = timestampLabelText
    self.messageText?.text = messageText


    self.messageText.delegate = self
    self.messageText.sizeToFit() //works, i can see different heights when giving a custom color background
    println(self.messageText.frame.height)

    }
}

我应该在我的自定义单元格类中设置高度吗?这没有任何意义,因为它还没有被渲染,不是吗?

€dit: 在“foo”处停止的屏幕截图:

【问题讨论】:

    标签: swift ios8 uicollectionview uicollectionviewcell


    【解决方案1】:

    bar 为零 因为 foo 为零 - 这就是可选链接“?”在该表达式中所做的事情。如果collectionView.cellForItemAtIndexPath(indexPath) as? MessageCell 为零,则意味着:

    • 该索引路径上没有单元格,或者
    • indexPath 的单元格不是MessageCell 的实例

    我建议它更有可能是后者,因为这些委托消息不应该真正使用无效的索引路径调用。您在哪里注册您的单元格类(在代码中或在情节提要中),您确定将它们注册为MessageCell 单元格吗?


    类型应以大写字符开头

    【讨论】: