TextView with dynamic height

1

I'd like to know how I can make my UITextView dynamic height, something like WhatsApp . I need that as the text is typed it will increase by itself.

Thanks in advance for your attention.

    
asked by anonymous 16.10.2015 / 01:46

1 answer

2

Once you set delegate in the header of your class:

class TesteViewController: UIViewController, UITextViewDelegate {

Then you implement the two methods below, with textViewDidChange you will set a new height each time the text is modified:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    return true
}

func textViewDidChange(textView: UITextView) {
    let maxHeight: CGFloat = 312.0
    let fixedWidth = textView.frame.size.width
    let newSize: CGSize = textView.sizeThatFits(CGSizeMake(fixedWidth, CGFloat.max))
    var newFrame: CGRect = textView.frame
    newFrame.size = CGSizeMake(fmax(newSize.width, fixedWidth), fmin(newSize.height, maxHeight))
    textView.frame = newFrame
}
    
16.10.2015 / 14:25