iOS虚拟键盘大小没有通知中心

时间:2013-03-26 21:07:01

标签: ios objective-c nsnotificationcenter virtual-keyboard

当需要点击虚拟键盘的textFiewl时,我需要向上滚动我的scrollView。我打电话给[self.scrollView setContentOffset:scrollPoint animated:YES];。要获得屏幕的可见区域,我显然需要KB大小。

我熟悉

NSDictionary *info = [notification userInfo];

CGSize kbSize = [self.view convertRect:
                 [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue]
                              fromView:nil].size;

然而,它对我不起作用,因为当用户点击可能半隐藏的文本字段时,我没有收到键盘通知。

所以我调用textFieldDidBeginEditing:中的方法,在键盘发送消息之前调用该方法,所以我不知道第一次点击时的KB大小。

所以问题是:是否可以获取KB大小,而无需调用相应的通知? Programmaticaly,而不是硬编码。

1 个答案:

答案 0 :(得分:3)

你做错了。

您还需要收听键盘显示/隐藏通知,然后调整屏幕。

以下是一个示例框架代码:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(keyboardChangedStatus:) name:UIKeyboardWillShowNotification object:nil];
    [nc addObserver:self selector:@selector(keyboardChangedStatus:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [nc removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - Get Keyboard size

- (void)keyboardChangedStatus:(NSNotification*)notification {
    //get the size!
    CGRect keyboardRect;
    [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardRect];
    keyboardHeight = keyboardRect.size.height;
    //move your view to the top, to display the textfield..
    [self moveView:notification keyboardHeight:keyboardHeight];
}

#pragma mark View Moving

- (void)moveView:(NSNotification *) notification keyboardHeight:(int)height{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationBeginsFromCurrentState:YES];

    CGRect rect = self.view.frame;

    if ([[notification name] isEqual:UIKeyboardWillHideNotification]) {
        // revert back to the normal state.
        rect.origin.y = 0;
        hasScrolledToTop = YES;
    } 
    else {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard (you need to adjust the value here)
        rect.origin.y = -height;
    }

    self.view.frame = rect;

    [UIView commitAnimations];
}