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

来源:互联网 发布:macbook免费办公软件 编辑:程序博客网 时间:2024/05/06 21:46

//先添加两个通知监听

- (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];

}

原创粉丝点击