您的位置:首页 > 其它

键盘事件监听

2015-12-21 15:44 281 查看
[code]在iOS开发中,键盘的事件是通过通知来进行处理,如果我们需要获取到键盘的高度,就需要去注册系统的键盘通知,并调用自定义的方法来实现监听。


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

[code]UIKIT_EXTERN NSString *const UIKeyboardWillShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidShowNotification;
UIKIT_EXTERN NSString *const UIKeyboardWillHideNotification;
UIKIT_EXTERN NSString *const UIKeyboardDidHideNotification;


使用就需要先向通知中心注册:(以其中一个为例)

[code][[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];


编写自定义方法

[code]- (void)keyboardWillShow:(NSNotification *)notif {

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


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

[code]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}}";
}


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

示例:

将textField(自定义)添加代理协议,并让控制器成为其代理。并注册键盘通知

创建一个全局的textField(currentTextField),表示当前点击要编辑的是哪一个textField.

在UITextFieldDelegate 代理方法中操作

[code]- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.currentTextField = textField; // 传送全局
    return YES;
}


在键盘通知事件中处理:

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


当键盘需要消失时,如果改变了形变需要将其调整过来

[code]- (void)keyboardWillHide:(NSNotification *)notif {
    // code
       self.currentTextField.superview.transform = CGAffineTransformIdentity;
 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: