获取ios设备键盘高度

时间:2021-09-26 00:32:41

使用cocos2dx 3.9版本开发时,有些UI需要根据键盘弹出高度自适应布局,而自带的TextField控件并未提供获取键盘高度的API,需要自己实现:

.h //oc接口头文件

@interface TKKeyBoard:NSObject

- (id)init;

- (void)keyboardWillShow:(NSNotification *)aNotification;

- (void)keyboardWillHide:(NSNotification *)aNotification;

@end

.mm

static std::function<void(bool show,int h)> m_keyBoardCallBack;

@implementation TKKeyBoard
-(id)init
{
    self = [super init];
    
    m_keyBoardCallBack=nullptr;
    //增加监听,当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听,当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    return self;
}


- (void)keyboardWillShow:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    int width = keyboardRect.size.width;
    NSLog(@"键盘宽度:高度  %d-%d",width,height);
    if (m_keyBoardCallBack) {
        m_keyBoardCallBack(true,width);
    }
}

- (void)keyboardWillHide:(NSNotification *)aNotification;
{
    if(m_keyBoardCallBack){
        m_keyBoardCallBack(false,0);
    }
}

@end

void tkKeyBoardCallBack(std::function<void(bool show,int h)> callback)
{
    m_keyBoardCallBack=callback;
}

.h //c++ 接口的头文件

#ifndef TKKeyBoardCpp.h
#define TKKeyBoardCpp.h

void tkKeyBoardCallBack(std::function<void(bool show,int h)> callback);


#endif /* TKKeyBoardCpp.h */


使用方法:

在AppController.mm 中 调用[[TKKeyBoard alloc] init]; 初始化监听

    在需要监听键盘行为的地方 设置tkKeyBoardCallBack() 回调