输入框随着键盘弹出上移

有个功能是点击输入框键盘弹出的时候不让遮挡,就是键盘弹起时输入框自动上移,效果如下:


效果图

具体实现代码:

//  KeyboardToMoveController.m
//  JSOCTest
//
//  Created by 贾倍 on 2018/4/17.
//  Copyright © 2018年 贾倍. All rights reserved.
//

#import "KeyboardToMoveController.h"

@interface KeyboardToMoveController (){
    UITextField *phoneNemberText;//手机号输入框
    UITextField *verifyCodeText;//密码输入框
}

@end

@implementation KeyboardToMoveController

- (void)viewDidLoad {
    [super viewDidLoad];
    phoneNemberText = [[UITextField alloc] initWithFrame:FRAME(100, SCREEN_HEIGHT*0.7, 100, 30)];
    phoneNemberText.placeholder = @"手机号";
    phoneNemberText.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:phoneNemberText];
    
    verifyCodeText = [[UITextField alloc] initWithFrame:FRAME(100, phoneNemberText.mr_bottom + 20, 100, 30)];
    verifyCodeText.placeholder = @"密码";
    verifyCodeText.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:verifyCodeText];
    
    //注册观察键盘的变化
    //键盘将要显示
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //键盘将要隐藏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    // Do any additional setup after loading the view.
}

-(void)keyboardWillShow:(NSNotification *)notification{
    //获取处于焦点中的view
    NSArray *textFields = @[phoneNemberText, verifyCodeText];
    UIView *focusView = nil;
    for (UITextField *view in textFields) {
        if ([view isFirstResponder]) {
            focusView = view;
            break;
        }
    }
    if (focusView) {
        //获取键盘弹出的时间
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //获取键盘上端Y坐标
        CGFloat keyboardY = [self getKeyboardY:notification.userInfo];
        //获取输入框下端相对于window的Y坐标
        CGPoint tmp = [self getViewOriginPointToWindow:focusView];
        CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
        //计算二者差值
        CGFloat ty = keyboardY - inputBoxY;
        NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
        //差值小于0,做平移变换
        [UIView animateWithDuration:duration animations:^{
            if (ty < 0) {
                self.view.transform = CGAffineTransformMakeTranslation(0, ty);
            }
        }];
    }
}

-(void)keyboardWillHide:(NSNotification *)notification{
    //获取键盘弹出的时间
    double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //还原
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

//处理iOS8之后键盘上端的Y坐标以及输入框下端相对于window的Y坐标
-(CGFloat)getKeyboardY:(NSDictionary *)userInfo{
    CGFloat screenHeight;
    CGFloat keyboardY = 0;
    CGFloat keyboardHeight = 0;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (([[[UIDevice currentDevice] systemVersion] floatValue]<8)  && UIInterfaceOrientationIsLandscape(orientation)) {
        screenHeight = [[UIScreen mainScreen] bounds].size.width;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.width;
        keyboardY = screenHeight - keyboardHeight;
    } else if (([[[UIDevice currentDevice] systemVersion] floatValue]<8)  && UIInterfaceOrientationIsPortrait(orientation)) {
        screenHeight = [[UIScreen mainScreen] bounds].size.height;
        keyboardHeight = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
        keyboardY = screenHeight - keyboardHeight;
    } else {
        keyboardY = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
    }
    return keyboardY;
}

//获取输入框下端的Y坐标
-(CGPoint)getViewOriginPointToWindow:(UIView *)view{
    CGPoint origin;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8) {
        CGPoint focusViewPoint = [view convertPoint:CGPointZero toView:nil];
        UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            origin.y = focusViewPoint.x;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
            origin.x = focusViewPoint.y;
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            origin.y = [[[UIApplication sharedApplication] delegate] window].bounds.size.height - focusViewPoint.y;
            origin.x = [[[UIApplication sharedApplication] delegate] window].bounds.size.width - focusViewPoint.x;
        } else {
            origin = focusViewPoint;
        }
    } else {
        CGRect rect = [view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
        origin = rect.origin;
    }
    return origin;
}

//点击空白区域让键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    for (UIView *view in self.view.subviews) {
        [view resignFirstResponder];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

你可能感兴趣的:(输入框随着键盘弹出上移)