2016-08-07 6 views
0

Я строю Chatting View Controller. ограничения моего пузыря чата являются следующими:bubble in Collection View не растет до соответствующей высоты

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, следующий код, который изменяет высоту и ширину 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, будучи привязанным к ячейке, также будет принимать высоту, где теперь вы можете видеть четкие пространство под текстом. Мне было интересно, есть ли более точные функции для оценки того, какая высота ячейки должна основываться на том, сколько текста есть.

enter image description here

ответ

0

Если вы используете UITextView тогда, Вы могли бы использовать этот метод:

import UIKit 
import XCPlayground 

let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 500)) 
view.backgroundColor = UIColor.whiteColor() 
XCPlaygroundPage.currentPage.liveView = view 

let text = "The function estimateframefortext estimates the frame of the cell based on the text (somehow, no idea how it does it). It works fine for messages under 600 characters or so, however, if you write more characters it adds an extra 20-30 of height to the cell, the bubbleView being constrained to the cell will also adopt the height, where you can now see clear space under the text. I was wondering if there were more precise functions to estimate what the height of a cell should be. \n!!!!!The function estimateframefortext estimates the frame oheightTextThe function estimateframefortext estimates the frame of the cell based on the text (somehow, no idea how it does it). It works fine for messages under 600 characters or so, however, if you write more characters it adds an extra 20-30 of height to the cell, the bubbleView being constrained to the cell will also adopt the height, where you can now see clear space under the text. I was wondering if there were more precise functions to estimate what the height of a cell should be " 

let label = UITextView() 
view.addSubview(label) 
label.text = text 

let size = label.sizeThatFits(CGSize(width: view.bounds.width, height: 0)) 
let heightText = size.height 
debugPrint(label.contentSize) 
label.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: heightText) 
label.layer.borderWidth = 1 
label.layer.borderColor = UIColor.redColor().CGColor 

или:

let label = UITextView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 0)) 
view.addSubview(label) 
label.text = text 
debugPrint(label.contentSize) 
label.frame.size = label.contentSize 
label.layer.borderWidth = 1 
label.layer.borderColor = UIColor.redColor().CGColor 

Объясните:

UITextView реализует поведение для прокручиваемый, когда вы помещаете контент [в этом случае , текст], textView соответствует протоколу UIScrollView, для этого вы можете использовать contentSize, которые возвращают размер представления содержимого.