I have tried 2 more methods. But those are not giving me the correct solution.
If i tried this one
func textViewDidChange(_ textView: UITextView) {
self.comments.translatesAutoresizingMaskIntoConstraints = true
self.comments.sizeToFit()
self.comments.isScrollEnabled = false
}
i can only type a one letter per a line.
If i tried this one
func textViewDidChange(_ textView: UITextView) {
self.comments.translatesAutoresizingMaskIntoConstraints = true
self.comments.isScrollEnabled = false
let fixedWidth = passedOut.frame.size.width
let newSize = comments.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
comments.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
}
Its working. But at the viewDidLoad stage, the width of textview is certain less than which i constraints to the textview. But i gave the leading, trailing , height as same as passedOut textfield to that textview.
If i start typing in textview, the width of textview will become exact size which i want.
So pls suggest me what mistake i made?
CodePudding user response:
Assign a height constraint to the text view
Use the following method to change the height:
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 { self.userMessageTextViewHeightConstraint.constant = newSize.height textView.layoutIfNeeded() } }
CodePudding user response:
You can achieve this behavior by doing 2 things in textview
- Disable scrolling in textview
- Assign the following constraints to textview
a) leading
b) trailing
c) top
d) height >= 30 ,assuming 30 is the minimum height of your textview.
Now when your text will grow textview will grow with it.