Reputation: 966
I need to be able to resize a UITableViewCell from within the cell according to the height of a UITextView object in the table view cell. As the user types more characters in the text view, the text view needs to increase in height and the table view cell needs to increase in height also to accomodate the height of the text view. I need to do this without UITableView.reloadData(), as I need the text view to remain first responder as the user types more characters into it.
I have tried using NSLayoutConstraint.deactivate(:), NSLayoutConstraint.activate(:), contentView.updateConstraints(), contentView.updateConstraintsAsNeeded(), contentView.setNeedsUpdateConstraints(), contentView.layoutIfNeeded() and UITextView.sizeToFit() with constraints on the height of the text view and on the contentView in different combinations.
I have not gotten it to work.
I include the code for my table view cell subclass. I put a comment where I tried all the code I mentioned.
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet weak var textView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
textView.delegate = self
textView.textContainer.lineBreakMode = .byWordWrapping
textView.isScrollEnabled = false
}
}
extension TableViewCell: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// !!! I tried the code here !!!
return true
}
}
In the table view controller I have this code:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
I can get the table view cell to resize when I use UITableView.reloadData(), but I can't get it to work otherwise.
I have looked at the other questions on StackOverflow and have not found a solution.
This helped
(How do I resize a UITableViewCell according to the size of a UITextView subView?)
but it solves the problem in a way that is not the intended way. I suspect the way Apple intends for this problem to be solved has to do with the other ways I've tried, namely using constraints.
I hope someone knows how to do what I want to do. Any help is appreciated.
Upvotes: 0
Views: 67
Reputation: 681
Since you have turned off the scrolling behaviour of textview
in your TableViewCell
, you can call the delegate to your view controller
when and call it when text changes.
protocol TextFieldUpdateDelegate {
func textFieldDidChangeText(_ textview: UITextView)
}
Now in your view controller's delegate conformance.
func textFieldDidChangeText(_ textView: UITextView) {
tableView.beginUpdate()
tableView.endUpdate()
}
According to docs:
You can also use this method followed by the endUpdates() method to animate the change in the row heights without reloading the cell.
And this should update the height of the tableview cell according to the contained text in the textView.
Upvotes: 2