【发布时间】:2016-08-07 01:26:51
【问题描述】:
我正在构建一个Chatting View Controller。我的聊天气泡的约束如下:
bubbleViewRightAnchor = bubbleView.rightAnchor.constraintEqualToAnchor(self.rightAnchor, constant: -8)
bubbleView.topAnchor.constraintEqualToAnchor(self.topAnchor).active = true
bubbleWidthAnchor = bubbleView.widthAnchor.constraintEqualToConstant(200)
bubbleWidthAnchor?.active = true
bubbleViewRightAnchor?.active = true
bubbleView.heightAnchor.constraintEqualToAnchor(self.heightAnchor).active = true
bubbleView 内部是一个textView,它被限制在bubbleView 内部,如下所示:
textView.leftAnchor.constraintEqualToAnchor(bubbleView.leftAnchor, constant: 8).active = true
textView.topAnchor.constraintEqualToAnchor(self.topAnchor).active = true
textView.rightAnchor.constraintEqualToAnchor(bubbleView.rightAnchor).active = true
textView.heightAnchor.constraintEqualToAnchor(self.heightAnchor).active = true
所有约束都正常工作,您可以看到聊天气泡的高度锚点被限制为“自我的高度锚点”,自我是collection View cell。因此,无论细胞有什么高度,气泡也会有。气泡内部是一个textView,其中包含用户发送的所有文本。在另一个View Controller中,以下代码根据textview中的文本数量修改collection view cell的高度和宽度如下:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var height: CGFloat = 80
if let text = messages[indexPath.item].text {
height = estimateFrameForText(text).height + 20
}
let width = UIScreen.mainScreen().bounds.width
return CGSize(width: width, height: height)
}
private func estimateFrameForText(text: String) -> CGRect {
let size = CGSize(width: 200, height: 1000)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
return NSString(string: text).boundingRectWithSize(size, options: options, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16)], context: nil)
}
函数estimateframefortext根据文本估计单元格的框架(不知何故,不知道它是如何做到的)。它适用于 600 个字符左右以下的消息,但是,如果您写入更多字符,它会为单元格增加额外 20-30 的高度,被限制到单元格的 bubbleView 也将采用高度,您现在可以见文字下方的空白处。我想知道是否有更精确的函数可以根据文本的多少来估计单元格的高度。
【问题讨论】:
标签: ios swift uicollectionview uibubbletableview