Textview with dynamic height

Asked

Viewed 76 times

1

I wonder how I do to leave mine UITextView with the dynamic height, something like the Whatsapp. I need as the text is typed the same increase alone.

Thanks in advance for your attention.

1 answer

2


Once you define the delegate in the header of your class:

class TesteViewController: UIViewController, UITextViewDelegate {

Then you implement the two methods below, being that the 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.