The Blocker Of Lower Views
I’m sure that like me when I was new, a lot of you guys started creating this nice UI, UITextfield, buttons, and after running your code, typing in your text, you go to click your fancy button only to realize half your screen is being blocked by a keyboard you don’t know how to dismiss.
We’ve all had this happen
Delegates To The Rescue
Luckily for you, this first part is very easy. You’ll first need to conform to the UITextFieldDelegate to use the function you need though. One tip to remember is in general, if you need something to happen when trying to use some of Apples built in functionality, you probably want to check out what the delegate does. Think “didSelectRow”, thats a delegate function.
The function youre looking for is called
textFieldDidReturn, lets see what Apples documentation has to say about this.
The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped. For example, if you want to dismiss the keyboard when the user taps the return button, your implementation can call the resignFirstResponder() method.
Four Easy Steps
That sounds like exactly what we want right? This requires very little code to accomplish, it’s a four part process.
- Make sure your textView is connected as an outlet.
- Conform to
- Call the function
textFieldShouldReturn, and inside of it, call
resignFirstResponder()on your textField.
- In your
viewDidLoad, make your textFields delegate is self.
This is what your code should look like if you’ve configured it correctly.
We have destroyed the blocker of lower views
Now, this is all fine if all you wanted to do was dismiss the keyboard when hitting your return button, but most applications these days also dismiss the keyboard when tapping anywhere outside of the keyboard. That will take a little more work than this, but fear not, thats what part 2 is for!