键盘出现时移动UIView

时间:2012-03-10 05:43:14

标签: iphone objective-c ios

对不起我的英语。

我试图在行动之前找到它。但问题在于景观中的ViewController并创建了UIView ViewController的一半。在UIView中有UITextView。但是现在当键盘在键盘下方的ViewController向下滚动时出现背景。只看UIView。如果触摸空间,键盘将消失,背景将恢复。我想只是在键盘出现时移动UIView

非常感谢。

2 个答案:

答案 0 :(得分:10)

试试这个

- (void)viewDidAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardBounds;
    NSValue *aValue = [note.userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];

    [aValue getValue:&keyboardBounds];
    keyboardHeight = keyboardBounds.size.height;
    if (!keyboardIsShowing)
    {
        keyboardIsShowing = YES;
        CGRect frame = view.frame;
        frame.size.height -= 168;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        view.frame = frame;
        [UIView commitAnimations];
    }
}

- (void)keyboardWillHide:(NSNotification *)note
{
    CGRect keyboardBounds;
    NSValue *aValue = [note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
    [aValue getValue: &keyboardBounds];

    keyboardHeight = keyboardBounds.size.height;
    if (keyboardIsShowing)
    {
        keyboardIsShowing = NO;
        CGRect frame = view.frame;
        frame.size.height += 168;

        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:0.3f];
        view.frame = frame;
        [UIView commitAnimations];

    }
}

答案 1 :(得分:1)

This answer看起来可能就是你要找的东西。

简而言之:

  1. 检测键盘何时出现 UIKeyboardDidShowNotification

  2. 该通知的user info描述了键盘的框架。

  3. 调整视图的框架,使其从键盘下方取出。