测试键盘在显示时是否隐藏文本字段

时间:2013-02-28 14:21:03

标签: ios

我在键盘显示时尝试向上移动,我的方法是测试键盘的框架和文本框架的框架是否相交。

- (void)keyboardDidShow:(NSNotification *)notification
{


    // Get the size of the keyboard.
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    //Test whether the current frame of the text field is hidden by the keyboard

    if (!CGRectIsNull(CGRectIntersection(keyboardFrame,self.activeField.frame))) {
        NSLog(@"Key board frame intersects with the text field frame");
    }


}

在上面的代码中,CGRectIsNull始终返回null。

调试语句返回以下信息:键盘和正在选择的活动文本字段:

键盘尺寸=(宽度= 352,高度= 1024) 键盘原点=(x = -352,y = 0)

键盘架=(-352,0,352,1024) 文本字段框架=(200,15,300,30)

每个文本字段都具有相同的帧值,这意味着出错了。那么如何测试键盘是否隐藏文本字段以便我上下移动表单。感谢名单。

2 个答案:

答案 0 :(得分:0)

我将整个内容放在全屏UIScrollView中,然后在需要时调整大小......

// This in your init somewhere
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

-(void) keyboardWillChange:(NSNotification*)notify {

    CGRect endFrame;
    float duration = [[[notify userInfo] valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [[[notify userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&endFrame];
    endFrame = [self.view convertRect:endFrame fromView:nil];
    float y = (endFrame.origin.y > self.view.bounds.size.height ? self.view.bounds.size.height : endFrame.origin.y);

    [UIView animateWithDuration:duration animations:^{
        scrollView.frame = CGRectMake(0, 0, self.view.bounds.size.width, y);
    }];

}

答案 1 :(得分:-1)

试试这个:

 [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {}];

并使用[note userInfo];

中的信息