iOS 键盘挡住输入框的解决方案

来源:互联网 发布:苹果cms解析 编辑:程序博客网 时间:2024/05/15 04:53

原理:利用通知来实现对键盘状态的监听
直接上代码
1.注册通知

/*       键盘即将弹出    UIKeyboardWillShowNotification     键盘已经弹出    UIKeyboardDidShowNotification     键盘即将隐藏    UIKeyboardWillHideNotification     键盘已经隐藏    UIKeyboardDidHideNotification     键盘frame变化    UIKeyboardWillChangeFrameNotification*/[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldShouldChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

2.实现通知方法

- (void)textFieldShouldChangeFrame:(NSNotification *)notification{    //通知中的字典信息    NSDictionary *dict = notification.userInfo;    CGRect beginRect = [dict[UIKeyboardFrameBeginUserInfoKey] CGRectValue];    CGRect endRect = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];    /* 键盘弹出高度变化 */    CGFloat changeY = beginRect.origin.y - endRect.origin.y;    /* 键盘弹出动画时间 */    NSTimeInterval time = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];    /* 利用动画改变键盘位置 */    [UIView animateWithDuration:time animations:^{        _textField.frame = CGRectMake(0, _textField.frame.origin.y - changeY, _textField.frame.size.width, _textField.frame.size.height);    }];}

3.移除通知

- (void)dealloc{    /* 移除通知 */    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];}
0 0