代码之家  ›  专栏  ›  技术社区  ›  Ivan Cantarino

基于UITextView属性化文本计算UICollectionViewCell高度

  •  0
  • Ivan Cantarino  · 技术社区  · 7 年前

    我有一个 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 回复  |  直到 7 年前
        1
  •  1
  •   NNikN    7 年前

    下面可能是简单ViewController的代码。

    enter image description here

    在这里,我只是将一些虚拟内容加载到 UITextView . 之后 UITextView UITableViewCell 设置为此 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()
        }
    
    
    
    
    }
    

    以简单的方式实现自动调整大小有三个关键点。

    1) 对于UITextView“已启用滚动”将其设置为 " .

    2) 将UITableView维度设置为自动并设置一些估计高度(我使用的是Xcode 9,但您可以使用 UITableView 属性) enter image description here

    您还可以检查下面附加的自动布局调整大小属性。

    enter image description here

    3) 现在,当您编辑textView时,可以让委托更新UITableView或在中重新加载特定的indexPath 开始更新 结束更新 . func textViewDidChange(_ textView: UITextView)