我正在構建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
裏面是存在於bubbleView
內部約束如下一個textView
:
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
,下面的代碼用於修改的高度和collection view cell
的寬度基於多少文本是在textview
如下:
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
也會採用高度,您現在可以看到清晰文字下的空間。我想知道是否有更精確的函數來估計單元格的高度應該基於多少文本。