First, create a UIWindow class, which is the key to non-intrusion resolution, then register to listen for keyboard events, calculate the position of the first responder when the keyboard opens, calculate the travel value, and move the keyWindow. Without further ado, go directly to the code:

//
// UIWindow+KeyBoard.m
// AIBillCore
//
// Created by luckAction on 2020/4/4.
// Copyright © 2020 Chenhenian. All rights reserved.
//

#import "UIWindow+KeyBoard.h"
#import <objc/runtime.h>
@interface UIWindow(a)
@property (nonatomic.strong) NSNumber *lastOffest;
@end
@implementation UIWindow (KeyBoard)

static NSString * offsetKey = @"offsetKey";

+ (void)initialize
{
    if (self= = [UIWindow class]) {
        
         // The keyboard pops up to add listening events
        // Notification of keyboard occurrence
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
        // Notification of keyboard disappearance
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil]; }} - (NSNumber*)lastOffest{
    return (NSNumber*)objc_getAssociatedObject(self, &offsetKey);
}

- (void)setLastOffest:(NSNumber *)lastOffest{
    objc_setAssociatedObject(self, &offsetKey, lastOffest, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


Pragma mark - Keyboard listening method
- (void)keyboardWasShown:(NSNotification *)notification
{
    if (!self.lastOffest) {
        self.lastOffest = [[NSNumber alloc] initWithShort:0];
    }
    // Get the height of the keyboard
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // Get the first responder
    UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
    
    CGRect tagViewRect = [firstResponder convertRect:firstResponder.bounds toView:keyWindow];
    CGFloat offest = frame.origin.y - tagViewRect.size.height - tagViewRect.origin.y - self.lastOffest.floatValue;

    if (offest < 0) {[UIView animateWithDuration:0.25 animations:^{
            keyWindow.transform = CGAffineTransformMakeTranslation(0.0);
        }];
    }
    self.lastOffest = [[NSNumber alloc] initWithShort:offest];
}
- (void)keyboardWillBeHiden:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 animations:^{
        [[UIApplication sharedApplication] keyWindow].transform = CGAffineTransformMakeTranslation(0, offest);
    }];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end
Copy the code


Code download, password: 1BU0