2022-05-07获取iOS设备键盘高度和动画弹出时间

获取iOS设备键盘高度和动画弹出时间

添加监听通知

如代码所示,监听通知,并添加方法

- (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];
}

实现通知响应方法

注意获取的是 UIKeyboardFrameEndUserInfoKey ,这个是变化后的值,如果获取到的值不是你想要的,变化一下对应的 KEY 直到取到你想要的值。

- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    //获取动画时间
    double animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //处理自己的业务逻辑
    [self.infoView handleKeyboardWillShowWithHeight:height Duration:animationDuration];
}
 
- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    //获取动画时间
    double animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //处理自己的业务逻辑
    [self.infoView handleKeyboardWillHideWithHeight:height Duration:animationDuration];
}

你可能感兴趣的:(2022-05-07获取iOS设备键盘高度和动画弹出时间)