iOS 监听键盘的弹出,收起,并且拿到键盘的高度

2017-11-11  本文已影响0人  IOSCoderYummy

监听当键盘将要出现时

OC版
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

监听当键将要退出时

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
swift版
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardShow(noty:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
        
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardHidden(noty:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
OC版

当键盘出现

- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
}

当键退出

- (void)keyboardWillHide:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height; 
} 
swift版

键盘弹出

@objc func keyBoardShow(noty: Notification) {
    guard let userInfo = noty.userInfo else {return}
    let value = userInfo["UIKeyboardFrameBeginUserInfoKey"] as! NSValue
    let keyboardRect = value.cgRectValue
    let keyboradHeight = keyboardRect.size.height
}

键盘退出

@objc func keyBoardShow(noty: Notification) {
    guard let userInfo = noty.userInfo else {return}
    let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
    let keyboardRect = value.cgRectValue
    let keyboradHeight = keyboardRect.size.height
}
上一篇 下一篇

猜你喜欢

热点阅读