监听键盘弹框动效

107 阅读1分钟
#import "LGKeyboardController.h"

@interface LGKeyboardController ()

@property (nonatomic, strong) UIView *bottomView;

@end

@implementation LGKeyboardController

- (void)viewDidLoad {
    [super viewDidLoad];

    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 89, [UIScreen mainScreen].bounds.size.width, 89);
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor lightGrayColor];
        UITextField *textField = [[UITextField alloc] init];
        textField.backgroundColor = [UIColor greenColor];
        [_bottomView addSubview:textField];
        textField.frame = CGRectMake(20, 10, [UIScreen mainScreen].bounds.size.width-40, 40);
    }
    return _bottomView;
}

//当键盘出现

- (void)keyboardWillShow:(NSNotification *)notification {
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    NSLog(@"keyboardWillShow");
    [UIView animateWithDuration:0.25 animations:^{
        self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - keyboardRect.size.height - 89, [UIScreen mainScreen].bounds.size.width, 89);
    }];
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification {
    NSLog(@"keyboardWillHide");
    [UIView animateWithDuration:0.25 animations:^{
        self.bottomView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 89, [UIScreen mainScreen].bounds.size.width, 89);
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

@end

Simulator Screen Shot - iPhone 13 Pro Max - 2022-04-29 at 17.03.28.png

Simulator Screen Shot - iPhone 13 Pro Max - 2022-04-29 at 17.03.34.png