0

嗨,有人可以帮我创建这个功能吗,我想在我的应用程序底部有一个文本框,一旦用户点击它,它应该将该文本框提升到键盘正上方的屏幕中间。类似于 Skype 应用程序,谢谢!在此处输入图像描述

在此处输入图像描述

4

1 回答 1

2

试试这个

#define kKeyboardAnimationDuration 0.3
@interface YourViewController:UIViewController
{
    BOOL keyboardIsShown;
}

然后在你的实现中

- (void)viewDidLoad
{
// register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];

    keyboardIsShown = NO;
}

- (void)viewDidUnload
{
[super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil]; 
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil]; 
}

#pragma mark - Keyboard Events
- (void)keyboardWillShow:(NSNotification *)n
{
    if (keyboardIsShown) 
    {
        return;
    }

    NSDictionary* userInfo = [n userInfo];
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y-= (keyboardSize.height);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = YES;
}

- (void)keyboardWillHide:(NSNotification *)n
{
    NSDictionary* userInfo = [n userInfo];
    CGSize keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y+= (keyboardSize.height);

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:kKeyboardAnimationDuration];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];

    keyboardIsShown = NO;
}
于 2012-07-04T00:24:23.467 回答