Resize text box based on content

How can I resize a text box based on content when using auto-layout in an iOS application written in Swift?

The text field will change as necessary to match its contents when loading the view, as well as when entering the user.

Ideally, a text field stops resizing at a certain point, say, 6 lines and becomes scrollable.

+7
ios resize swift textfield
source share
2 answers

You should use a UITextView instead of a UITextField .

Then you can use the sizeThatFits method.

But first you need to know what one line will be. You can get this information with lineHeight :

 var amountOfLinesToBeShown: CGFloat = 6 var maxHeight: CGFloat = yourTextview.font.lineHeight * amountOfLinesToBeShown 

After that, just call the sizeThatFits method inside your viewDidLoad method and set maxHeight ( line * 6 ) as the height of your textview:

 yourTextview.sizeThatFits(CGSizeMake(yourTextview.frame.size.width, maxHeight)) 
+8
source share

Swift 3

 var textView : UITextView! override func viewDidLoad() { super.viewDidLoad() textView = UITextView() textView.sizeThatFits(CGSize(width: textView.frame.size.width, height: textView.frame.size.height)) } 
+1
source share

All Articles