Resize UITableViewCell containing UITextView upon typing

后端 未结 11 2071
感动是毒
感动是毒 2020-12-23 10:19

I have an UITableViewController that contains a custom cell. Each cell was created using a nib and contains a single non-scrollable UITextView. I have added constraints insi

11条回答
  •  囚心锁ツ
    2020-12-23 10:57

    Using Swift 2.2 (earlier versions would likely work too), if you set the TableView to use auto dimensions (assuming you're working in a subclassed UITableViewController, like so:

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 50 // or something
    

    You just need to implement the delegate in this file, UITextViewDelegate, and add the below function, and it should work. Just remember to set your textView's delegate to self (so, perhaps after you've dequeued the cell, cell.myTextView.delegate = self)

    func textViewDidChange(textView: UITextView) {
        self.tableView.beginUpdates()
        textView.frame = CGRectMake(textView.frame.minX, textView.frame.minY, textView.frame.width, textView.contentSize.height + 40)
        self.tableView.endUpdates()
    }
    

    Thanks to "Jose Tomy Joseph" for inspiring (enabling, really) this answer.

提交回复
热议问题