Tuesday, July 16, 2013

iOS7 > Lesson #1b - Hide the Keyboard (First Responder)

Background

In this lesson, you can learn:
  • Hide the keyboard when the users touches Return key by using First Responder
  • Hide the keyboard when the users taps the background by calling touchBegan: event handler
  • Further Study: other similar event handler
When user enters data in iOS7 app, the keyboard automatically appears on the screen.
However, the keyboard does not automatically go away when the user has finished typing.

If you have experience of using other iPhone or iPad apps, you will have noticed that pressing the Return key on the keyboard or tapping anywhere on the background of the user interface usually causes the keyboard to recede (i.e. disappear) from view.

In actual fact, developers of these apps had to write some codes to implement this functionality.



Step#1: To create a new Project named with "HideKeyboard"

- Single View Application template
- Drag (i.e. Control + Left Click) the text field Outlet object with named "textField" as Type "UITextField" to interface file (.h file)


HideKeyboardViewController.h

- Compile & Run once
Keyboard can be shown when type text in textfield



Step#2: To write up method with FirstResponder

resignFirstResponder method



Step#3: To wire up ViewController with action

1. Click the yellow button for ViewController at the bottom

2. Drag "textFieldReturn:" in Received Actions under Connection Tab to the text field and select "Did End on Exit".


4. Compile & Run
Keyboard is dismissed when the user touch Return key

Step#4: To wire up ViewController with action

1. To hide the keyboard when the user touches the background view of the screen (or any view other than the text field), we will implement the touchesBegan event handler method on the view controller. This method will need to check that the object being touched by the user is not the textField itself.


touchesBegan: method

Step#5: Reference

http://www.techotopia.com/index.php/Writing_iOS_7_Code_to_Hide_the_Keyboard

https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UIResponder_Class/Reference/Reference.html



http://www.cnblogs.com/spiritstudio/archive/2011/05/26/2059352.html
<codes are different from websites !!!>



Step#6: Further Study on similar event handler

1. To touch the screen:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
2. To move on the screen:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
3. To leave from the screen:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
4. To cancel the touching the screen (e.g. During time, incoming call is disturbed):
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

No comments:

Post a Comment