iOS 键盘弹出时获取键盘的高度

时间:2022-05-30 00:32:33


1、在viewDidLoad方法中加入监测键盘的通知。

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardWillHidden:)name:UIKeyboardWillHideNotificationobject:nil];

}

2、实现通知的方法

/**

 *  键盘将要显示

 *

 *  @param notification 通知

 */

-(void)keyboardWillShow:(NSNotification *)notification

{

//这样就拿到了键盘的位置大小信息frame,然后根据frame进行高度处理之类的信息

    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    

    CGFloat endHeight =self.showScrollView.contentSize.height + frame.size.height;

    self.showScrollView.contentSize =CGSizeMake(SCREEN_WIDTH, endHeight);

    self.showScrollView.contentOffset =CGPointMake(0,self.bottomView.originY);

}

/**

 *  键盘将要隐藏

 *

 *  @param notification 通知

 */

-(void)keyboardWillHidden:(NSNotification *)notification

{

    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    

    CGFloat endHeight =self.showScrollView.contentSize.height - frame.size.height;

    self.showScrollView.contentSize =CGSizeMake(SCREEN_WIDTH, endHeight);

}