Ali Ihsan URAL
Ali Ihsan URAL

Reputation: 1974

Swift - TextView Heigth & Width change when typing

I want to resize the textview when typing but with this codes I didnt change the width. Everytime I get the textView size as 200. Where is the mistake? Please help to me.

Thanks in advance

let textViewX = UITextView(frame: CGRect(x: self.view.frame.width / 2 - 100, y: self.view.frame.height / 2 - 25, width: 200, height: 50))
textViewX.isScrollEnabled = false
textViewX.clipsToBounds = false
textViewX.delegate = self
textViewX.font = UIFont.systemFont(ofSize: 25)
self.view.addSubview(textViewX)


func textViewDidChange(_ textView: UITextView) {
    let fixedWidth = textView.frame.size.width
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
    textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
}

Upvotes: 0

Views: 502

Answers (1)

Jbryson
Jbryson

Reputation: 2905

Your issue is that you are telling the newSize that it cannot be any wider than fixedWidth by using the sizeThatFits(:) method. If you change your code to allow a greater width, your textView will grow horizontally:

let fixedHeight = textView.frame.size.height
let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: fixedHeight))
textView.frame.size = newSize

This allows the textView's frame to grow only horizontally. To allow both you might try something like this:

let maxWidth = UIScreen.main.bounds.width - 20
let maxHeight = UIScreen.main.bounds.height - 20
let newSize = textView.sizeThatFits(CGSize(width: maxWidth, height: maxHeight))
textView.frame.size = newSize
textView.center = view.center

This allows the frame to grow vertically and horizontally, keeping the textView centered in its parent view, and limiting the textView's size to the screen's size (with a 20 pt boarder all around).

Upvotes: 2

Related Questions