iphone开发之——自动适应键盘的高度

//先添加两个通知监听

- (void) registerForKeyboardNotifications {

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:)name:UIKeyboardDidHideNotification object:nil];

}

//显示键盘后

- (void) keyboardWasShown:(NSNotification *) notif{ 

    NSDictionary* userInfo = [notif userInfo];

    NSTimeInterval animationDuration;

    UIViewAnimationCurve animationCurve;

    CGRect keyboardFrame;

    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKeygetValue:&animationCurve];

    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKeygetValue:&animationDuration];

    [[userInfo objectForKey:UIKeyboardBoundsUserInfoKeygetValue:&keyboardFrame];

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:animationDuration];

    [UIView setAnimationCurve:animationCurve];

    [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - keyboardFrame.size.height, self.view.frame.size.width, self.view.frame.size.height)];

    [UIView commitAnimations];

//隐藏键盘后

- (void) keyboardWasHidden:(NSNotification *) notif{ 

    NSDictionary* userInfo = [notif userInfo];

    NSTimeInterval animationDuration;

    UIViewAnimationCurve animationCurve;

    CGRect keyboardFrame;

    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKeygetValue:&animationCurve];

    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKeygetValue:&animationDuration];

    [[userInfo objectForKey:UIKeyboardBoundsUserInfoKeygetValue:&keyboardFrame];

    [UIView beginAnimations:nil context:nil];

    [UIView setAnimationDuration:animationDuration];

    [UIView setAnimationCurve:animationCurve];

    [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + keyboardFrame.size.height, self.view.frame.size.width, self.view.frame.size.height)];

    [UIView commitAnimations];

}

你可能感兴趣的:(iphone开发之——自动适应键盘的高度)