iOS8 / Swift:UICollectionViewCell高度计算

时间:2015-03-16 17:49:03

标签: swift ios8 uicollectionview uicollectionviewcell

从关于这个主题的其他帖子中得出我尝试了以下方法 - 但不知何故" 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)

    }
}

我应该在自定义单元格类中设置高度吗?这没有任何意义,因为它还没有呈现,不会吗?

€二叔: 停在" foo"的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:0)

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

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

我建议它更可能是后者,因为那些委托消息不应该使用无效的索引路径调用。在您注册单元类的位置(在代码中或在故事板中),您确定要将它们注册为MessageCell单元格吗?


类型应以大写字母

开头