4

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

我熟悉

NSDictionary *info = [notification userInfo];

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

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

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

所以问题是:是否可以在不调用相应通知的情况下获得 KB 大小?以编程方式,而不是硬编码。

4

1 回答 1

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];
}
于 2013-03-26T21:37:39.360 回答