As you can see in this image
the UITextView
changes it\'s height according to the text length, I want to make it adjust it\'s height according to the te
Swift 4+
This is extremely easy with autolayout! I'll explain the most simple use case. Let's say there is only a UITextView
in your UITableViewCell
.
textView
to the contentView
with constraints.textView
.tableView
in textViewDidChange
. (You can do the last step in two ways - either pass the tableView instance to the cell or set the textView delegate to your view controller and implement the textViewDidChange
delegate there and update the table view.)
That's all!
class TextViewCell: UITableViewCell {
//MARK: UI Element(s)
/// Reference of the parent table view so that it can be updated
var tableView: UITableView!
lazy var textView: UITextView = {
let textView = UITextView()
textView.isScrollEnabled = false
// Other textView properties
return textView
}()
//MARK: Padding Variable(s)
let padding: CGFloat = 50
//MARK: Initializer(s)
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubviews()
addConstraints()
textView.becomeFirstResponder()
}
//MARK: Helper Method(s)
func addSubviews() {
contentView.addSubview(textView)
}
func addConstraints() {
textView.leadingAnchor .constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
textView.trailingAnchor .constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
textView.topAnchor .constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
textView.bottomAnchor .constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TextViewCell: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
Check out my repo for the full implementation.