键盘事件监听

在iOS开发中,键盘的事件是通过通知来进行处理,如果我们需要获取到键盘的高度,就需要去注册系统的键盘通知,并调用自定义的方法来实现监听。        

键盘通知事件有以下几种:

UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;
  1. 使用就需要先向通知中心注册:(以其中一个为例)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  1. 编写自定义方法
- (void)keyboardWillShow:(NSNotification *)notif {

    NSLog(@"%s:%@",__func__,notif);
    CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kBoardHeight = rect.size.height; // 可以取出键盘的高度
}

打印通知的的UserInfo信息如下:(其中第三行就可以看出键盘的尺寸了)

userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 441.5}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 694.5}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 315}, {320, 253}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 568}, {320, 253}}";
}

如果需要处理类似根据键盘弹出,调整视图中待编辑的文本框不被键盘遮盖;就需要先获取键盘高度,再让文本框的父视图的形变发生改变即可。

示例:

  1. 将textField(自定义)添加代理协议,并让控制器成为其代理。并注册键盘通知
  2. 创建一个全局的textField(currentTextField),表示当前点击要编辑的是哪一个textField.
  3. 在UITextFieldDelegate 代理方法中操作
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.currentTextField = textField; // 传送全局
    return YES;
}
  1. 在键盘通知事件中处理:
- (void)keyboardWillShow:(NSNotification *)notif {
    CGRect rect = [[notif.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kBoardHeight = rect.size.height; // 可以取出键盘的高度
    CGPoint actuP = self.currentTextField.bounds.origin;
    // 当前textfield在window中的位置:
    CGPoint currentP = [self.currentTextField convertPoint:actuP toView:[UIApplication sharedApplication].keyWindow];

    // 根据情况判断正在编辑的神图是否被遮盖住
    CGFloat restH = kScreenH - currentP.y - self.currentTextField.bounds.size.height - 5; // 尺寸可随自己需要调整
    if (restH < kBoardHeight) { // 说明预留尺寸不够,需要再移动视图位置保证尺寸足够
        [UIView animateWithDuration:.5 animations:^{
            self.currentTextField.superview.transform = CGAffineTransformMakeTranslation(0, restH - kBoardHeight);
        }];
    }
}
  1. 当键盘需要消失时,如果改变了形变需要将其调整过来
- (void)keyboardWillHide:(NSNotification *)notif {
    // code
       self.currentTextField.superview.transform = CGAffineTransformIdentity;
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值