2017-03-17 9 views
1

メッセージタイプのアプリケーションを作成しています。これは、さまざまな長さのテキストを含むUITextViewのブロックで構成され、これらは「バブル」UIViewにあります。一部のテキストのUICollectionViewセルのサイズを見積もる

let textView: UITextView = { 
    let text = UITextView() 
    text.text = "SAMPLE" 
    text.translatesAutoresizingMaskIntoConstraints = false 
    text.backgroundColor = .clear 
    text.textColor = .white 
    return text 
}() 
let bubbleView: UIView = { 
    let view = UIView() 
    view.backgroundColor = UIColor(r: 0, g: 137, b: 247) 
    view.layer.cornerRadius = 14 
    view.layer.masksToBounds = true 
    view.translatesAutoresizingMaskIntoConstraints = false 
    return view 
}() 
var bubbleWidthAnchor: NSLayoutConstraint? 

    bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true 
    bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 
    bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 250) 
    bubbleWidthAnchor?.isActive = true 
    bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true 

    textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true 
    textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 
    textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true 
    textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true 

私は正常に動作していないに が想定しているカスタム関数を使用していたセルの高さを設定します。

カスタム機能:

私は UICollectionViewため sizeForItemAt関数内で呼び出す
private func estimatedFrameForText(text: String) -> CGRect { 
    let size = CGSize(width: 250, height: 250) 
    let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) 

    return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)], context: nil) 
} 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 
    var height: CGFloat = 80 //Arbitrary number 
    if let text = messages[indexPath.item].text { 
     height = estimatedFrameForText(text: text).height + 8 
    } 
    return CGSize(width: view.frame.width, height: height) 
} 

私が午前の単純な問題は、それが素晴らしい働いていません...です: Example

私が間違っているかどうか、または私が必要とする推定サイズを得るためのより良い解決策テキストに応じて、セル?

答えて

2

私が見逃していたのは、textViewのテキストサイズを設定することでした。

attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16) 

をですから、両方が同じになるように定義する必要が:関数が推定サイズを持って取得するためにtext.font = UIFont.systemFont(ofSize: 16)を置く

が必要でした。

関連する問題