2017-10-15 58 views
0

我有一个UICollectionViewCell,它有一个UITextView作为其子视图,锚定到单元格的边界。计算UICollectionViewCell height base don 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的代码。

enter image description here

如果我只是加载在的UITextView的一些虚拟内容。 之后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“滚动已启用”将其设置为“”。

2)设置的UITableView尺寸为自动,并设置一些预测的高度(我用的Xcode 9,但您可以设置与的UITableView属性) enter image description here

您还可以检查自动布局调整属性附后。

enter image description here

3)现在,当你编辑的TextView你可以委托更新的UITableView或重新加载特定indexPath在beginUpdatesendUpdatesfunc textViewDidChange(_ textView: UITextView)