Touching the background to close the keyboard
Go to Xcode if you haven't already. We need to add one more action to our controller class. Add the following line to the Control_FunViewController.h file:
Save the header file; go to the implementation file and add this code that just tells both text fields to get the status of the first responder, if he has one. It is perfectly safe to call resignFirstResponder on a control that is not the first responder, so we can safely call it in both text fields without checking if it is the first responder.
- (IBAction)backgroundTap:(id)sender { [nameField resignFirstResponder]; [numberField resignFirstResponder]; }
TIP Save this file and return to Interface Builder. Now we need to change the base class of the nibs view. If you look at the main nibs window, you will see that there are three icons in this view. The third, called View, is the main nibs view, which contains all the other controls and views as subzones. Click the View icon once, which is a view of the nibs container. Press ␣4 to call up the identity inspector. Here we can change the base class of any instance of the object in Interface Builder.
You will repeatedly switch between header files and implementation during encoding. Fortunately, Xcode has a keyboard shortcut that quickly switches you between these files. The default keyboard shortcut is ␣␣␣ (option-command-arrow), although you can change it to whatever you want using Xcodes preferences.
The box labeled Class is currently specifying UIView. Change it to read UIControl. All controls that can trigger action methods are subclasses of UIControl, so by changing the base class, we just gave this view the ability to run action methods. You can check this by pressing ␣2 to call the connection inspector.
Drag from the Touch Down event to the File Owner icon and select the backgroundTap: action. Now, touching anywhere in the view without an active control will call our new action method, which will make the keyboard fall back.
Note Save the tip and go back and try. Compile and run the application again. This time, the keyboard should disappear not only when the “Finish” button is pressed, but also when you click anywhere where there is no active control, and this is the behavior that your user will expect.
rptwsthi Aug 09 2018-11-11T00: 00Z
source share