简单的监听键盘出现和消失的方法以及得到键盘高度

来源:互联网 发布:男士欧莱雅护肤品淘宝 编辑:程序博客网 时间:2024/06/06 03:33

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

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    

    [[NSNotificationCenter defaultCenteraddObserver:selfselector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenteraddObserver:selfselector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];

}

2、实现通知的方法

/**

 *  键盘将要显示

 *

 *  @param notification 通知

 */

-(void)keyboardWillShow:(NSNotification *)notification

{

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

    CGRect frame = [[[notification userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    

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

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

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

}

/**

 *  键盘将要隐藏

 *

 *  @param notification 通知

 */

-(void)keyboardWillHidden:(NSNotification *)notification

{

    CGRect frame = [[[notification userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    

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

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

}

0 0
原创粉丝点击