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
Change the size when typing
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
yourTextView.translatesAutoresizingMaskIntoConstraints = true
yourTextView.sizeToFit()
yourTextView.isScrollEnabled = false
let calHeight = yourTextView.frame.size.height
yourTextView.frame = CGRect(x: 16, y: 193, width: self.view.frame.size.width - 32, height: calHeight)
}
Change the size when load
func textViewNotasChange(arg : UITextView) {
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.isScrollEnabled = false
let calHeight = arg.frame.size.height
arg.frame = CGRect(x: 16, y: 40, width: self.view.frame.size.width - 32, height: calHeight)
}
Call the function of the second option like this:
textViewNotasChange(arg: yourTextView)
this Works for me, all other solutions didn't.
func adjustUITextViewHeight(arg : UITextView)
{
arg.translatesAutoresizingMaskIntoConstraints = true
arg.sizeToFit()
arg.scrollEnabled = false
}
In Swift 4 the syntax of arg.scrollEnabled = false
has changed to arg.isScrollEnabled = false
.
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
Swift 5, Use extension:
extension UITextView {
func adjustUITextViewHeight() {
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
Usecase:
textView.adjustUITextViewHeight()
And don't care about the height of texeView in the storyboard (just use a constant at first)
its working
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textviewconclusion.frame.size.width
textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textviewconclusion.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textviewconclusion.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textviewconclusion.frame = newFrame
}
Swift 4
Add It To Your Class
UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame
}