美文网首页
iOS 监听键盘的弹出,收起,并且拿到键盘的高度

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

作者: IOSCoderYummy | 来源:发表于2017-11-11 13:52 被阅读0次

监听当键盘将要出现时

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
}

相关文章

网友评论

      本文标题:iOS 监听键盘的弹出,收起,并且拿到键盘的高度

      本文链接:https://www.haomeiwen.com/subject/hacfmxtx.html