13

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.

Michael Voccola
  • 1,827
  • 6
  • 20
  • 46

2 Answers2

12

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))
Christopher Smit
  • 953
  • 11
  • 27
Christian
  • 22,585
  • 9
  • 80
  • 106
  • Why do you use 2 times the `yourTextview.sizeThatFits(…)`? – milo526 Apr 11 '15 at 17:04
  • is there any way we can increase the number of lines of a UITextField? @Christian – Manu Gupta May 06 '15 at 10:04
  • 1
    @ManuGupta No. You have to use an `UITextView` if you want the multiline-feature. – Christian May 06 '15 at 10:44
  • 1
    i did all inside viewdidload but my textfield didn't increase.let amountOfLinesToBeShown:CGFloat = 4 let maxHeight:CGFloat = textView.font!.lineHeight * amountOfLinesToBeShown textView.sizeToFit() textView.sizeThatFits(CGSizeMake(textView.frame.size.width, maxHeight)) i want to increase my textview according to size of content and must not be greater than certain height. – Prashant Ghimire Oct 26 '16 at 07:12
  • I used this method But in CGSizeMake I got Error so I Changed this to CGSize.init And Run success But the problem is that text view still has just two lines to be shown! @Christian – Saeed Rahmatolahi May 29 '17 at 05:03
3

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))
}
SpaceX
  • 2,814
  • 2
  • 42
  • 68