Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize textField Based On Content

How can a textField be resized based on content while using auto-layout in an iOS application written in Swift?

The text field will resize as necessary to fit its content when the view loads as well as while the user is typing.

Ideally, the text field would stop resizing at a certain point, say, 6 lines, and become scrollable.

like image 912
Michael Voccola Avatar asked Feb 08 '15 02:02

Michael Voccola


People also ask

What is UITextField?

An object that displays an editable text area in your interface.

How do I increase the height of a textfield in Swift?

Click the attribute inspector for the textField and then change the Border style to second one and you will be able to change the height.


1 Answers

You have to use an UITextView instead of an UITextField.

Then, you can use the sizeThatFits method.

But first you have to know how high one line will be. You can get that information by using 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 the maxHeight (line * 6) as your textview height:

yourTextview.sizeThatFits(CGSizeMake(yourTextview.frame.size.width, maxHeight))
like image 169
Christian Avatar answered Oct 07 '22 03:10

Christian