2017-10-15 14 views
0

私はサブビューとしてUITextViewを持ち、セルの境界に固定されているUICollectionViewCellを持っています。計算UICollectionViewCell高さベースドンUITextView帰属テキスト

UITextView attributedStringに基づいて達成しようとしているのは、UITextViewの高さを計算し、スクロールしないようにしてセルの高さにそのサイズを適用することです。

ここで問題となるのは、NSAttributedStringのフォントサイズが異なる可能性があり、画像サイズが大きくなることがあります。

複数の内部フォーム(サイズ、改行、イメージ)を持つことができるそのコンテンツに基づいて、サイズを計算するにはどうすればよいですか?

私は次の関数を適用するために使用しますが、それはこのケースでは動作しません

、内側のコンテンツので、フォントサイズが延期するように、それは一定ではない。

private func estimatedHeightForText(_ text: String) -> CGFloat { 
    let approximateWidthOfBioTextView = view.frame.width - 24 // paddings 
    let size = CGSize(width: approximateWidthOfBioTextView, height: 1000) // height of 1000 is an arbitrary value 
    let attributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)] // attributes of the text 

    // gets the estimation height based on Text 
    let estimatedFrame = NSString(string: text).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) 
    return estimatedFrame.height 
} 

任意のヒント?

ありがとうございました。

答えて

1

以下は、単純なViewControllerのコードです。私はちょうどUITextViewでいくつかのダミーのコンテンツをロードしています

enter image description here

UITableViewCellUITextViewの代理人は、このViewControllerに設定されます。

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UITextViewDelegate { 

    @IBOutlet var tableView:UITableView! 
    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func numberOfSections(in tableView: UITableView) -> Int { 
     return 1 
    } 

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 2 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cellId = "textCell" 
     let cell = tableView.dequeueReusableCell(withIdentifier: cellId)! 

     return cell 

    } 

    func textViewDidChange(_ textView: UITextView) { 
     tableView.beginUpdates() 
     tableView.endUpdates() 
    } 




} 

簡単な方法で自動サイズ変更を達成するには3つの重要なポイントがあります。

1)UITextViewの場合、「Srolling Enabled」に「NO」を設定します。

2)自動へのUITableViewサイズを設定し、いくつかの推定高さ(私はXcodeの9を使用していますが、あなたはのUITableViewプロパティで設定することができます) enter image description here

を設定するまた、以下に添付の属性のサイズを変更する自動レイアウトを確認することができます。

enter image description here

3)あなたがのTextViewを編集するときに今、あなたは、デリゲートは、のUITableViewを更新したり、beginUpdatesendUpdates内の特定のindexPathをリロードすることができます。 func textViewDidChange(_ textView: UITextView)

関連する問題