I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var messageTextView: UITextView!
let messageTextViewMaxHeight: CGFloat = 100
override func viewDidLoad() {
super.viewDidLoad()
self.messageTextView.delegate = self
}
func textViewDidChange(textView: UITextView) {
if textView.frame.size.height >= self.messageTextViewMaxHeight {
textView.scrollEnabled = true
textView.frame.size.height = self.messageTextViewMaxHeight
} else {
textView.scrollEnabled = false
}
}
}
It seems your code requires two changes, and it will work fine.
Change code as below:
After many many hours of problems with textviews in table view cells, this was the solution that worked for me. I'm using Masonry, but the constraints could be created in IB as well.
Note that the textview delegate is not used. This is advantageous because it doesn't matter whether you change the text programmatically or via user input. Either way layoutSubviews gets called whenever a text view changes its contents.
If you want to have this directly in your view controller you could use
viewDidLayoutSubviews
instead oflayoutSubviews
.This follows a similar approach to the accepted answer but ensures the
textView
is fully constrained in both height states.(There's a bug in the accepted answer - using a height constraint with a
<=
relation is insufficient to fully constrain thetextView
when scrolling is enabled, since in this case the view provides nointrinsicContentSize
. You can see this in IB (with scrolling disabled), or at runtime via view debugging.)This is all that's necessary:
There's no need to set frames manually, since in both cases auto-layout has us covered.
For an easy way to solve your problem is to change the frame of the textView whenever textViewDidChange invokes. UITextView actually is a UIScrollView. If you have to use constraint, you have to change the constant of the constraint. Here is my code:
Maybe the code below is a little better.