iOS开发自适应键盘高度

来源:互联网 发布:java教程视频百度云 编辑:程序博客网 时间:2024/06/16 05:24

一、通过获取键盘消息的状态,以及变化周期,可以计算出具体的Y偏移,改变视图的位置。   

        //注册键盘出现的通知        [[NSNotificationCenter defaultCenter] addObserver:self                                                  selector:@selector(keyboardWasShown:)                                                      name:UIKeyboardWillShowNotification object:nil];        //注册键盘消失的通知        [[NSNotificationCenter defaultCenter] addObserver:self                                                  selector:@selector(keyboardWillBeHidden:)                                                      name:UIKeyboardWillHideNotification object:nil];- (void)keyboardWasShown:(NSNotification*)aNotification{    //键盘高度    CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];    [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{        _bgScrollView.frameY=-keyBoardFrame.size.height;            } completion:^(BOOL finished) {    }];    }-(void)keyboardWillBeHidden:(NSNotification*)aNotification{    [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{        _bgScrollView.frameY=0;            } completion:^(BOOL finished) {            }];        } 





二、使用第三方插件(IQKeyboardManage)

IQKeyboardManager 支持 CocoaPods

platform :ios, '8.0'

pod "IQKeyboardManager","~> 3.3.5"  

使用方法如下

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {         IQKeyboardManager *manager = [IQKeyboardManager sharedManager];    manager.enable = YES;    manager.shouldResignOnTouchOutside = YES;    manager.enableAutoToolbar = NO;    return YES;}

其中enable控制整个功能是否启用。

shouldResignOnTouchOutside控制点击背景是否收起键盘。

shouldToolbarUsesTextFieldTintColor 控制键盘上的工具条文字颜色是否用户自定义。


如果想要控制某个单独页面则在页面代理中设置

-(void)viewDidAppear:(BOOL)animated{    [super viewDidAppear:animated];    [[IQKeyboardManager sharedManager] setEnable:NO];}-(void)viewWillDisappear:(BOOL)animated{    [super viewWillDisappear:animated];    [[IQKeyboardManager sharedManager] setEnable:YES];   } 





1 0
原创粉丝点击