iOS分享一个无入侵解决键盘遮挡的方案

1,267 阅读1分钟

首先,创建一个UIWindow的分类,这是无入侵解决的关键点,然后注册监听键盘事件,在键盘打开时,计算第一响应者的位置,算出差值,移动keyWindow。话不多说,直接上码:

//
//  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()
@property (nonatomic, strong) NSNumber *lastOffest;
@end
@implementation UIWindow (KeyBoard)

static NSString * offsetKey = @"offsetKey";

+ (void)initialize
{
    if (self == [UIWindow class]) {
        
         //键盘弹出添加监听事件
        // 键盘出现的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
        // 键盘消失的通知
        [[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 -键盘监听方法
- (void)keyboardWasShown:(NSNotification *)notification
{
    if (!self.lastOffest) {
        self.lastOffest = [[NSNumber alloc] initWithShort:0];
    }
    // 获取键盘的高度
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //获取第一响应者
    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


代码下载, 密码:1bu0