Resize Textfield Based on Content

Resize textField Based On Content

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))

Textarea to resize based on content length

You can check the content's height by setting to 1px and then reading the scrollHeight property:





function textAreaAdjust(element) {
element.style.height = "1px";
element.style.height = (25+element.scrollHeight)+"px";
}
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>

iOS UITextField Auto Resize conform to the content

With a UITextField, text must fit on one line and cannot wrap.

You have two options:

  1. Shrink the font to fit on one line:

    self.TextFieldExample.adjustsFontSizeToFitWidth = YES;
    self.TextFieldExample.minimumFontSize = 10.0; //Optionally specify min size

  2. Use UITextView to enable text wrapping:

    See this answer: How to create a multiline UITextfield?

p.s. Per the style guide, "Properties should be camel-case with the leading word being lowercase." so you should rename your var to self.textFieldExample



Related Topics



Leave a reply



Submit