Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When set UITextField as FirstResponder programmatically, cause some weird actions on text editing

I have a UITextField with custom keyboard, basically like a calculator. I would like my keyboard show up by default, so i used [self.topInputTextField becomeFirstResponder]; in viewDidLoad, I think that's very common usage. However, it causes some very weird actions on my textfield.

When i set my textfield as the first responder in viewDidLoad, and every time after i done editing, the text will jump, and when i click another text field and and click the first text field again, the texts in the first text field sometimes shift down and disappear, but sometimes not. I feel it's very hard to describe, so i recorded a GIF image for it.

enter image description here

And the reason, that I am sure [self.topInputTextField becomeFirstResponder]; causing the issue, is when i comment that line of code out, everything back to normal. here is the GIF after i comment out that line:

enter image description here

that's vert strange to me, between 2 GIF file, the only change i did is comment out that line of code. I couldn't find any solution on SE. Any idea would be very appreciated.

Edit: One more thing is I tried to change font, and font sizes, they all have similar strange behaviors.

*Edit 2:** here is how i set up my textfield,i didn't do anything fancy

enter image description here

like image 717
Xu Yin Avatar asked Jan 11 '23 04:01

Xu Yin


2 Answers

Try calling the keyboard in viewDidAppear, this method gets called after viewDidLoad. I assume it's because you should only call the keyboard on a loaded view that has appeared to the user, so if you call it before the view actually appears it will cause unexpected behaviour.

like image 60
David P Avatar answered Jan 22 '23 20:01

David P


viewDidLoad is too early for calling this, the UI hasn't worked out which size your screen is, or even which orientation your device is in. It isn't yet a UI really... Try it in willAppearAnimated: ..

like image 30
Jef Avatar answered Jan 22 '23 21:01

Jef