0

I have a UITextField with a label next to it that says "meter". The idea is that you can type a number in the textfield and the word "meter" will show next to it. The text field has no borders so it will look like one line of text when you're not editing the text field.

For this I need the text field's width to be the width of the text. So it needs to get wider as you type. However, this does not happen when you type. But if you rotate the device the size does adjust to the content. So basically I need to trigger whatever triggers when you rotate to get what I want.

I've tried lots of stuff in the UIControlEvents.editingChanged method like setNeedsLayout, setNeedsDisplay, layoutSubViews(), setNeedsUpdateConstraints(), but no luck.

Another approach was to use sizeToFit() and then set the frame.size.width to a width constraint of the text field. This did work, but only the first time you edit. When you edit the second time the sizeToFit() always returns te same somehow.

Any ideas?

Update: I ended up using a different approach. I made the text field full width and placed the meter label on top of it. As you type it calculates the width of the text and the meter label moves to the right accordingly by changing the left constraint constant. This way the label is always right next to the entered number.

I still haven't found a way to make a text field's width change as you type without acting all buggy, but I don't really need it anymore though.

Janneman
  • 1,093
  • 15
  • 23
  • Please Check http://stackoverflow.com/questions/18236661/resize-a-uitextfield-while-typing-by-using-autolayout I think this is the same question. –  Dec 16 '16 at 16:07

1 Answers1

0

I think you should perform inside

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

This function just decide whether or not the newly typed character should be appended at the end of the TextField's contentView. This function is called every time when the user types.

I think UIControlEvents.editingChanged only notifies you when the textField get focus or lost focus but not when the value changed.

Cosmos Man
  • 593
  • 3
  • 15
  • @Janneman. I hope this is helpful to you. I got the same problem while writing a project. I solved it programmatically. – Cosmos Man Dec 19 '16 at 07:32