UITextView and cell dynamically update height based on content of textview?

Deadly 提交于 2019-11-29 08:43:34

This works for ios 7 too

this goes into your tableviewcell

protocol HeightForTextView {
    func heightOfTextView(height: CGFloat)

}

class TableViewCell: UITableViewCell {

    @IBOutlet weak var textView: UITextView!

    var delgate:HeightForTextView?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func textViewDidChange(textView: UITextView) {

        var fixedWidth: CGFloat = textView.frame.size.width
        var newSize: CGSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max))

        if let iuDelegate = self.delgate {

            iuDelegate.heightOfTextView(newSize.height)
        }


    }

}

your tableview controller should be

 class TableViewController: UITableViewController,HeightForTextView {

        var textViewHeight = CGFloat()

    //In your cell for row method set your your delegate 
 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell
    cell.delgate = self

    return cell
}


//delegate method

    func heightOfTextView(height: CGFloat) {

    textViewHeight = height
    self.tableView.beginUpdates()
    self.tableView.endUpdates()

    }

 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

            return textViewHeight + 70
    }

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!