Я решил дать этому шанс, и он работает хорошо.Он предназначен для UITableView, который возвращает только 1 строку, поэтому вам нужно проделать немного больше работы, чтобы отслеживать ячейки в реальном приложении.
Это класс UITableViewCell:
import UIKit
class Cell: UITableViewCell {
@IBOutlet weak var textView: UITextView!
}
Cell.xib Content View содержит только UITextView.Я установил высоту строки на 44, а затем Ограничения TextView.top = top, bottom = TextView.bottom, trailing = TextView.trailing + 36, TextView.leading = lead + 36. 36 для ведущих и конечных ограничений неважно, я просто хотел немного места по бокам.
Вот весь ViewController:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {
@IBOutlet weak var tableView: UITableView!
private var textViewHeight: CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = 44
tableView.tableFooterView = UIView()
tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "cell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
cell.textView.delegate = self
cell.textView.text = ""
cell.textView.layer.borderColor = UIColor.lightGray.cgColor
cell.textView.layer.borderWidth = 1
cell.textView.layer.cornerRadius = 4
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return min(75, max(textViewHeight, 44))
}
func textViewDidChange(_ textView: UITextView) {
let size = textView.bounds.size
let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.greatestFiniteMagnitude))
if size.height != newSize.height {
textViewHeight = newSize.height
UIView.setAnimationsEnabled(false)
tableView.beginUpdates()
tableView.endUpdates()
UIView.setAnimationsEnabled(true)
}
}
}