Ios:iphone keyboard notification and keyboard customization

Source: Internet
Author: User

I. Keyboard notifications

When the text view (such as uitextfield,uitextview, input box inside UIWebView) enters edit mode to become first responder, the keyboard is automatically displayed. Becoming FirstResponder can be triggered by a user clicking on the trigger or sending a becomefirstresponder message to a text view. When the text view exits first responder, the keyboard disappears. Text view exit first responder may be triggered by the user tapping the done or return key on the keyboard to end the input, or by sending a resignfirstresponder message to the text view.

When the keyboard is displayed or disappears, the system sends the relevant notification:
Uikeyboardwillshownotification
Uikeyboarddidshownotification
Uikeyboardwillhidenotification
Uikeyboarddidhidenotification

The UserInfo dictionary in the notification message nsnotification contains the location and size information for the keyboard, and the corresponding key is

Uikeyboardframebeginuserinfokey
Uikeyboardframeenduserinfokey
Uikeyboardanimationdurationuserinfokey
Uikeyboardanimationcurveuserinfokey

The uikeyboardframebeginuserinfokey,uikeyboardframeenduserinfokey corresponding value is a Nsvalue object that contains the CGRect structure internally. Position information, respectively, when the keyboard starts and when it terminates.

The value of Uikeyboardanimationcurveuserinfokey corresponds to the NSNumber object, which is an internal uiviewanimationcurve type of data that represents the type of animation that the keyboard displays or disappears.

The value of Uikeyboardanimationdurationuserinfokey corresponds to the NSNumber object, which is a double-type data that represents the duration of the animation when the keyboard h is displayed or disappears.

For example, the UserInfo content in the Uikeyboardwillshownotification,uikeyboarddidshownotification notification is

userInfo = {    UIKeyboardAnimationCurveUserInfoKey = 0;    UIKeyboardAnimationDurationUserInfoKey = "0.25";    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 588}";    UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 372}";    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";    UIKeyboardFrameChangedByUserInteraction = 0;    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";}

In the Uikeyboardwillhidenotification,uikeyboarddidhidenotification notification
UserInfo content is:

userInfo = {    UIKeyboardAnimationCurveUserInfoKey = 0;    UIKeyboardAnimationDurationUserInfoKey = "0.25";    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 216}}";    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 372}";    UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 588}";    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 264}, {320, 216}}";    UIKeyboardFrameChangedByUserInteraction = 0;    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 480}, {320, 216}}";}

On Text,web, and Editing Programming Guide for iOS, there are descriptions note:the rectangle contained in the Uikeyboardframebeginuserinfoke Y and Uikeyboardframeenduserinfokey properties of the UserInfo dictionary should be used only for the size information it Contains. The origin of the rectangle (which is always {0.0, 0.0}) in rectangle-intersection operations. Because the keyboard is animated to position, the actual bounding rectangle of the keyboard changes over time.
However, from the actual information obtained, the origin of the rectangle is not {0.0, 0.0}, this should not be accurate.

Two. Text objects and WebView keyboard settings

Both uitextfiled and Uitextview follow the Uitextinputtraits protocol, which defines the properties of the keyboard set in the Uitextinputtraits protocol, with

1. Keyboardtype: Keyboard type, such as Uikeyboardtypedefault,uikeyboardtypeurl,uikeyboardtypeemailaddress, Uikeyboardtypephonepad, etc.

2. Returnkeytype: The text that the keyboard return key displays, the default is "return", other optional include go,next,done,send,google and so on.

3. Keyboardappearance: keyboard appearance, the default is Uikeyboardappearancedefault, that is, in the light blue opaque background, there is another one for Uikeyboardappearancealert,
The keyboard background is black translucent for display when the warning box is entered, such as when entering a password in AppStore:


If you want to display a black keyboard and do not want to reveal the bottom view transparently, you can configure the keyboard to be alert type, and then listen to the broadcast notification displayed by the keyboard, adding an opaque black background view at the bottom of the keyboard when the keyboard is displayed.

Note: In Apple's keyboard sample program keyboardaccessory, to change the Uitextview keyboard type to Uikeyboardappearancealert, running the keyboard in the ipad simulator does not appear to have a black transparent effect, do you know why? Uikeyboardappearancealert settings in iphone are valid.

4.autocapitalizationType: Text case style, see Uitextautocapitalizationtype.
5.autocorrectionType: If auto correct, see Uitextautocorrectiontype.
6.spellCheckingType: Spell check settings, see Uitextspellcheckingtype.
7. enablesreturnkeyautomatically: Whether to disable the return key when there is no text, the default is No. If yes, the user enters at least one word specifier return key to be activated.
8. Securetextentry: If you enter a password, you can set this type to Yes, you can display the last character when you enter a character, and other characters appear as points.

The UIWebView itself does not follow the Uitextinputtraits protocol directly, but it can also set the keyboard properties of its internal input parts. As described in configuring the Keyboard for Web views.

Set AutoCorrect, Auto-capitalization property.

<input type="text" size="30" autocorrect="off" autocapitalization="on">

To set the keyboard type:

Text: <input type="text"></input>Telephone: <input type="tel"></input>URL: <input type="url"></input>Email: <input type="email"></input>Zip code: <input type="text" pattern="[0-9]*"></input>
Three. Adjust the text view position with keyboard notifications

When the text view becomes first Responser, the keyboard appears at the bottom of the window, and the keyboard that appears is likely to cover the text view so you can't see the editing effect. One of the key uses of keyboard notifications is to get the position information of the keyboard when the keyboard is displayed or hidden, so that you can adjust the position or size of the text view in the window so that it can be displayed above the keyboard.

Text, Web, and Editing Programming Guide for iOS moving
Content that is Located under the keyboard section in the keyboard display and disappearance notification by adjusting the contents Uiscrollview view Contentinset and Contentoffset to ensure that the edited text view is not covered by the keyboard.

Its process is
1. When initializing (Viewdidload or viewwillappear), register the method that handles keyboard notifications.

- (void)registerForKeyboardNotifications{    [[NSNotificationCenter defaultCenter] addObserver:self            selector:@selector(keyboardWasShown:)            name:UIKeyboardDidShowNotification object:nil];   [[NSNotificationCenter defaultCenter] addObserver:self             selector:@selector(keyboardWillBeHidden:)             name:UIKeyboardWillHideNotification object:nil];}

2. In the notification event processing that is displayed on the keyboard, get the size of the keyboard that will be displayed, and set the  uiscrollview Contentinset to the frame area of the keyboard. Also set Scrollindicatorinsets to ensure that the scroll bar is not covered by the keyboard. Gets the origin position of the edit text view, compared to the keyboard display area, if it is overridden by the keyboard, adjust the  contentoffset so that it is

on the keyboard.

 //Called when the uikeyboarddidshownotification is sent.-(void) Keyboardwasshown: (nsnotification*)    anotification{nsdictionary* info = [Anotification userInfo];    Cgsize kbsize = [[info objectforkey:uikeyboardframebeginuserinfokey] cgrectvalue].size;    Uiedgeinsets contentinsets = uiedgeinsetsmake (0.0, 0.0, kbsize.height, 0.0);    Scrollview.contentinset = contentinsets;    Scrollview.scrollindicatorinsets = contentinsets; If Active Text field is hidden by keyboard, scroll it so it's visible//Your application might not need or want thi    s behavior.    CGRect arect = self.view.frame;    ARect.size.height-= Kbsize.height; if (! Cgrectcontainspoint (Arect, ActiveField.frame.origin)) {Cgpoint ScrollPoint = cgpointmake (0.0, ACTIVEFIELD.FRAME.O        Rigin.y-kbsize.height);    [ScrollView Setcontentoffset:scrollpoint Animated:yes]; }}

3. In the notification processing event that the keyboard disappears, simply restore the Uiscrollview to

// Called when the UIKeyboardWillHideNotification is sent- (void)keyboardWillBeHidden:(NSNotification*)aNotification{    UIEdgeInsets contentInsets = UIEdgeInsetsZero;    scrollView.contentInset = contentInsets;    scrollView.scrollIndicatorInsets = contentInsets;}

In the Apple Keyboardaccessory sample program, you also demonstrated the code that uses keyboard notifications to adjust the position of the text view, which uses keyboard animation time in the keyboard notification to synchronize the animation of the text view movement with the display and disappearance of the keyboard.

-(void) Keyboardwillshow: (nsnotification *) Notification {/* Reduce the size of the text view so it's not obsc     Ured by the keyboard.     Animate The resize so, it's in sync with the appearance of the keyboard.    */Nsdictionary *userinfo = [notification UserInfo];    Get The origin of the keyboard when it ' s displayed.    nsvalue* avalue = [UserInfo Objectforkey:uikeyboardframeenduserinfokey]; Get the top of the keyboard as the Y coordinate of its origin in Self's view ' s coordinate system.    The bottom of the text view ' s frame should align with the top of the keyboard ' s final position.    CGRect keyboardrect = [Avalue cgrectvalue];    Keyboardrect = [Self.view convertrect:keyboardrect fromview:nil];    CGFloat keyboardtop = KEYBOARDRECT.ORIGIN.Y;    CGRect newtextviewframe = self.view.bounds;    NewTextViewFrame.size.height = KEYBOARDTOP-SELF.VIEW.BOUNDS.ORIGIN.Y;    Get the duration of the animation. Nsvalue *animationdurationvalue = [UserInfo OBJECTFOrkey:uikeyboardanimationdurationuserinfokey];    Nstimeinterval animationduration;    [Animationdurationvalue getvalue:&animationduration];    Animate The resize of the text view ' s frame in sync with the keyboard ' s appearance.    [UIView Beginanimations:nil Context:null];    [UIView setanimationduration:animationduration];    Textview.frame = Newtextviewframe; [UIView commitanimations];}    -(void) Keyboardwillhide: (nsnotification *) Notification {nsdictionary* userInfo = [notification UserInfo];     /* Restore the size of the text view (fill self ' s view).     Animate The resize so, it's in sync with the disappearance of the keyboard.    */Nsvalue *animationdurationvalue = [UserInfo Objectforkey:uikeyboardanimationdurationuserinfokey];    Nstimeinterval animationduration;    [Animationdurationvalue getvalue:&animationduration];    [UIView Beginanimations:nil Context:null];    [UIView setanimationduration:animationduration]; Textview.frame = Self.view.bounds; [UIView commitanimations];}

You can also implement a custom keyboard in keyboard notifications, such as Uikeyboardtypenumberpad and the MISSING "return" key, which uses keyboard notifications to add the RETURN key to the numeric keypad. Also refer to Uikeyboardtypenumberpad keyboard to add return key

Note: If there are two Uitextfield in the same window, and when the first Uitextfield becomes primary responser, the keyboard is displayed and the Uikeyboardwillshownotification is received, Uikeyboarddidshownotification notifies you that when first Responser is transferred to the second Uitextfield, the keyboard will always be displayed, and you will not receive Willshow and didshow notifications at this time.

Four. Customizing input views with Inputaccessoryview and Inputview

inputaccessoryview and  inputview properties are defined in  uiresponder as ReadOnly properties, but in uitextfiled and   Uitextview is redefined in order to readwrite properties that can be assigned by the user. If  inputview is not nil, then when the text view becomes first responder, the system keyboard is not displayed, but the custom Inputview is displayed, and if Inputaccessoryview is not
Nil, The Inputaccessoryview will appear above the system keyboard or custom Inputview. When using Inputview, there will still be willshow,didshow,willhide,didhide keyboard notifications, Beginframe and endframe in the Notification system keyboard (or Inputview) Frame together with the Inputaccessoryview.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.