Возможно, вы неправильно делаете пару вещей ...
Во-первых, чтобы «автоматически изменить» высоту textView, у него должна быть прокрутка отключена .
Во-вторых, он не может иметь фиксированную высоту (ни ограничение по высоте, ни ограничение сверху и снизу).
Редактировать: Для пояснения ... Когда я говорю "нет нижнего ограничения", это не означает, что не может иметь нижнее ограничение. Скорее, нижнее ограничение не может быть установлено таким образом, чтобы препятствовал изменению высоты textView. Так, например, если textView находится в ячейке табличного представления, с нижним ограничением все в порядке, если ячейка спроектирована и используется таким образом, что высота textView контролирует (или способствует) высоту ячейки. .
Это простой пример, который переключает textView между 4 строками и нулевыми строками (показывая все текстовое содержимое):
class ExpandingTextViewViewController: UIViewController {
let descriptionTextView: UITextView = {
let v = UITextView()
v.translatesAutoresizingMaskIntoConstraints = false
// disable scrolling
v.isScrollEnabled = false
// give it a background color to make it easy to see the frame
v.backgroundColor = .yellow
return v
}()
let theButton: UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = .red
v.setTitle("Toggle TextView", for: .normal)
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(theButton)
view.addSubview(descriptionTextView)
NSLayoutConstraint.activate([
// button 40-pts from the top, centered horizontally
theButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
theButton.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0.0),
// textView 40-pts from bottom of button, 20-pts padding left and right
// NO height or bottom constraint
descriptionTextView.topAnchor.constraint(equalTo: theButton.bottomAnchor, constant: 40.0),
descriptionTextView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20.0),
descriptionTextView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20.0),
])
// give the textView some sample text
descriptionTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
// start with max number of lines set to 4
descriptionTextView.textContainer.maximumNumberOfLines = 4
theButton.addTarget(self, action: #selector(toggleTextView), for: .touchUpInside)
}
@objc func toggleTextView() -> Void {
// toggle max number of lines between 4 and Zero
descriptionTextView.textContainer.maximumNumberOfLines =
(descriptionTextView.textContainer.maximumNumberOfLines == 4) ? 0 : 4
// tell auto-layout abour the change
descriptionTextView.invalidateIntrinsicContentSize()
}
}
Результаты:
Конечно, вам нужно добавить некоторый код для обработки случая, когда ваш textView имеет столько текста, что он будет выходить за пределы нижней части экрана (или за пределы своего суперпредставления) - либо путем проверки полученного результата. высота, настройка и переключение прокрутки или встраивание textView в UIScrollView
(например).