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.

Documentation

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.

  1. Make sure your textView is connected as an outlet.
  2. Conform to UITextFieldDelegate.
  3. Call the function textFieldShouldReturn, and inside of it, call resignFirstResponder() on your textField.
  4. In your viewDidLoad, make your textFields delegate is self.

This is what your code should look like if you’ve configured it correctly.

Picture showing the correct code

We have destroyed the blocker of lower views

Part 2

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!

Stay Fresh

Using UIAlertController In Swift

5 Things I Wish I’d Been Told When I Decided To Be An iOS Developer