iOS--keyboard monitor Jykeyboardlistener

Source: Internet
Author: User
Tags uikit

No preface, is a simple keyboard monitoring, automatically adjust the position of the input box is not obscured by the keyboard

. h

////JYKeyBoardListener.h////Created by Jianf.sun on 17/9/26.//Copyright 2017 SJF. All rights reserved.///*function: 1, the input box is blocked by the keyboard, the entire view up (when the input box above the keyboard) 2, the keyboard pops up, add a button to hide the keyboard 3, prohibit a controller using Jykeyboardlistener: 1, Introduction of JYKeyBoardListener.h 2, program start: [Jykeyboardlistener Usejykeyboardlistener]; 3, some controllers do not want to use: [Jykeyboardlistener UNUSEDIN:VC]; Processing: 1, monitoring keyboard display, hidden, back to the backstage, into the foreground; 2, get the current top controller, 3, get the currently edited input box in Self.view frame, 4, the keyboard display hidden animation, 5, Hide the keyboard button add 6, handle push, Present keyboard display hidden problem (remember that the code endediting before push, because the push operating system does not automatically exit the keyboard) 7, processing self.view than the screen small problem (that is, Self.view does not scale to the bottom of the navigation bar) 8, Handling input boxes that appear incomplete on the screen*/#import<Foundation/Foundation.h>#import<UIKit/UIKit.h>@interfaceJykeyboardlistener:nsobject//called when the program starts+ (void) Usejykeyboardlistener;//prohibit the use of Jykeyboardlistener in Viewcontroller+ (void) Unusedin: (uiviewcontroller*) Viewcontroller;@end

. m

////JYKEYBOARDLISTENER.M////Created by Jianf.sun on 17/9/26.//Copyright 2017 SJF. All rights reserved.//#import "JYKeyBoardListener.h"#definekbl_screen_height [UIScreen mainscreen].bounds.size.heightNSString*Constjykeyboard_unused_key=@"Jykeyboard_unused_key";@interfaceJykeyboardlistener () @property (nonatomic,strong) UIView*Inputview, @property (nonatomic,strong) UIButton*resignbtn, @property (nonatomic,strong) UIView*lastview;//record a previous view that needs to be processed, solve the keyboard hidden problem when push,present operation//@property (Nonatomic,strong) Uiviewcontroller *UNUSEDVC;@end@implementationJykeyboardlistener#pragmaMark-interface method, which can be called Directly + (void) usejykeyboardlistener{[Jykeyboardlistener Sharejykeyboardlistener];}+ (void) Unusedin: (uiviewcontroller*) viewcontroller{Jykeyboardlistener*manager =[Jykeyboardlistener Sharejykeyboardlistener]; [[Nsuserdefaults Standarduserdefaults] Setvalue:[manager Getmemory:viewcontroller] forKey:JYKeyboard_Unused_Key];}#pragmaMark-Single Case +(instancetype) Sharejykeyboardlistener {StaticJykeyboardlistener *jykeyboardlistener =Nil; Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{Jykeyboardlistener=[[Jykeyboardlistener alloc] init]; //Monitor Keyboard[[Nsnotificationcenter defaultcenter] Addobserver:jykeyboardlistener selector: @selector (keyboardwillshowactio N:) name:uikeyboardwillshownotificationObject: nil]; [[Nsnotificationcenter Defaultcenter] Addobserver:jykeyboardlistener selector: @selector (keyboardwillhideaction:) Name:uikeyboardwillhidenotificationObject: nil]; [[Nsnotificationcenter Defaultcenter] Addobserver:jykeyboardlistener selector: @selector (enterbackground:) Name: UiapplicationdidenterbackgroundnotificationObject: nil]; [[Nsnotificationcenter Defaultcenter] Addobserver:jykeyboardlistener selector: @selector (enterforeground:) Name: UiapplicationwillenterforegroundnotificationObject: nil];        }); returnJykeyboardlistener;}#pragmaMark-keyboard display and hidden listening methods/** * Keyboard is about to pop up*/- (void) Keyboardwillshowaction: (Nsnotification *) note{if([Self currentmemory]!=nil&&[[Self currentmemory] isequaltostring:[self getmemory:[self Topviewcontroller]])        {[self addresignbtn:[self topviewcontroller].view]; return; }Else{[[Nsuserdefaults standarduserdefaults] Setvalue:nil Forkey:jykeyboard_unused_key]; }        //at the end of the keyboard frameCGRect ENDF =[Note.userinfo[uikeyboardframeenduserinfokey] cgrectvalue]; //Keyboard HeightCGFloat Keyboardh =EndF.size.height; //keyboard pop-up time requiredCGFloat Duration =[Note.userinfo[uikeyboardanimationdurationuserinfokey] doublevalue]; //the current ViewUIView *firstrspview =[self findfirstresponsderview]; if(firstrspview==Nil) {        //NSLog (@ "is empty");        return ; }    //Find the input box[self findsubview:firstrspview]; //gets the frame of the input box relative to the bottom view of the current displayCGRect Inputframe =[self getAbsoluteFrame:self.inputView]; //CGFloat difh = Cgrectgetmaxy (inputframe)-(kbl_screen_height-Keyboardh); //2. Animations[UIView animatewithduration:duration animations:^{                if(difh>0) {Firstrspview.transform= Cgaffinetransformmaketranslation (0,-DIFH); }Else{firstrspview.transform=cgaffinetransformidentity; } _lastview=Firstrspview; }completion:^(BOOL finished) {[Self addresignbtn:firstrspview]; } ];}/** * Keyboard is about to be hidden*/- (void) Keyboardwillhideaction: (Nsnotification *) note{//determine if the current controller is disabled    if([Self currentmemory]!=nil&&[[Self currentmemory] isequaltostring:[self getmemory:[self Topviewcontroller]]) {                return; }Else{[[Nsuserdefaults standarduserdefaults] Setvalue:nil Forkey:jykeyboard_unused_key]; }    //1. Time required for keyboard popupCGFloat Duration =[Note.userinfo[uikeyboardanimationdurationuserinfokey] doublevalue]; UIView*firstrspview =[self findfirstresponsderview]; if(firstrspview==Nil) {        return; }    if(_lastview&&_lastview!=firstrspview) {//before resuming when processing a jump, the push must_lastview.transform=cgaffinetransformidentity; _lastview=Nil; return; }    //2. Animations[UIView animatewithduration:duration animations:^{firstrspview.transform=cgaffinetransformidentity; }completion:^(BOOL finished) {}];}#pragmaMark-Foreground background switch processing-(void) Enterbackground: (nsnotification*) note{[[Self findfirstresponsderview] endediting:yes];}- (void) Enterforeground: (nsnotification*) note{}#pragmaMark-Hide Keyboard button-(void) Addresignbtn: (uiview*) firstrspview{if(self.resignbtn) {[self.resignbtn Removefromsuperview]; } self.resignbtn=[UIButton Buttonwithtype:uibuttontypecustom]; Self.resignBtn.backgroundColor=[Uicolor Clearcolor];    [Self.resignbtn addtarget:self Action: @selector (Hidekeyboard) forcontrolevents:uicontroleventtouchupinside]; Self.resignBtn.frame=Firstrspview.bounds;    [Firstrspview AddSubview:self.resignBtn]; [Firstrspview sendSubviewToBack:self.resignBtn];}- (void) hidekeyboard{[[Self findfirstresponsderview] endediting:yes]; Dispatch_async (Dispatch_get_main_queue (),^{[self.resignbtn removefromsuperview]; });}#pragmaMark-Other accessible methods/** Find the root controller view @return return Firstresponsderview*/-(uiview*) findfirstresponsderview{Uiviewcontroller*RETURNVC; //find the current root controllerRETURNVC =[self topviewcontroller]; if(RETURNVC) {returnReturnvc.view; }Else{        returnNil; }}//gets the Viewcontroller of the current screen display-(Uiviewcontroller *) Topviewcontroller {Uiviewcontroller*RESULTVC; RESULTVC=[self _topviewcontroller:[[uiapplication sharedapplication].keywindow rootviewcontroller];  while(resultvc.presentedviewcontroller) {RESULTVC=[self _topviewcontroller:resultvc.presentedviewcontroller]; }    returnRESULTVC;}-(Uiviewcontroller *) _topviewcontroller: (Uiviewcontroller *) VC {if([VC Iskindofclass:[uinavigationcontrollerclass]]) {        return[Self _topviewcontroller:[(Uinavigationcontroller *) VC Topviewcontroller]]; } Else if([VC Iskindofclass:[uitabbarcontrollerclass]]) {        return[Self _topviewcontroller:[(Uitabbarcontroller *) VC Selectedviewcontroller]]; } Else {        returnVC; }    returnNil;}/*gets the frame of the input box relative to the root controller view*/-(CGRect) Getabsoluteframe: (uiview*) view{UIView*mainview =[self findfirstresponsderview]; UIWindow*window =[UIApplication Sharedapplication].keywindow; CGRect rect=[view ConvertRect:view.bounds Toview:mainview]; //handling navigation bar issues    if(Cgrectgetheight (Mainview.bounds) <cgrectgetheight (window.bounds)) {RECT.ORIGIN.Y+ = Cgrectgetheight (window.bounds)-cgrectgetheight (mainview.bounds); }    //the frame returned by the scroll view is removed Scrollview.contentoffset.y    if([MainView Iskindofclass:[uiscrollviewclass]]|| [MainView Iskindofclass:[uitableviewclass]]|| [MainView Iskindofclass:[uiwebviewclass]]) {Uiscrollview*scrollview = (uiscrollview*) MainView; RECT.ORIGIN.Y-=Scrollview.contentoffset.y; if(Cgrectgetmaxy (rect) >kbl_screen_height) {//The input box is not fully displayed.//Remove off-screen height valuesRect.origin.y-=cgrectgetmaxy (Rect)-Kbl_screen_height; }    }        returnrect;}/*recursive method to find the input box*/- (void) Findsubview: (uiview*) view{ for(UIView *subviewinchview.subviews) {        if([SubView Isfirstresponder]) {//NSLog (@ "Find input box");Self.inputview =SubView; }Else{[Self findsubview:subview]; }    }}-(nsstring*) GetMemory: (uiviewcontroller*) vc{//controller name + content address of memory address +view    return[NSString stringWithFormat:@"jykeyboard%@%p%p", Nsstringfromclass ([VCclass]), Vc,vc.view];}-(nsstring*) currentmemory{return[[Nsuserdefaults standarduserdefaults] valueforkey:jykeyboard_unused_key];}@end

iOS--keyboard listener Jykeyboardlistener

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.