考虑到项目多处使用监听来处理键盘弹出时的页面遮挡问题 就讲键盘监听的响应事件用block封装在工具类中。实现方法如下
.h文件
//添加键盘监听
typedef void (^keyBoardWillShowAction) (CGFloat keyBoardHight);
typedef void (^keyBoardWillDissMissAction) (CGFloat keyBoardHight);
@property (nonatomic, copy) keyBoardWillShowAction showBlock;
@property (nonatomic, copy) keyBoardWillDissMissAction dissMissBlock;
- (void)addKeyBoardObservershowBlock:(keyBoardWillShowAction)showBlockAction dissMissAction:(keyBoardWillDissMissAction)dissMissAction;
.m文件:
- (void)addKeyBoardObservershowBlock:(keyBoardWillShowAction)showBlockAction dissMissAction:(keyBoardWillDissMissAction)dissMissAction;
{
self.showBlock = showBlockAction;
self.dissMissBlock = dissMissAction;
//监听当键盘将要出现时
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//监听当键将要退出时
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [value CGRectValue];
CGFloat height = keyboardRect.size.height;
self.showBlock(height);
}
//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
NSDictionary *userInfo = [notification userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [value CGRectValue];
CGFloat height = keyboardRect.size.height;
self.dissMissBlock(height);
}
使用方法
[[APIString shareInstance] addKeyBoardObservershowBlock:^(CGFloat keyBoardHight) {
[UIView animateWithDuration:0.5 animations:^{
//出现时候的事件
}];
} dissMissAction:^(CGFloat keyBoardHight) {
[UIView animateWithDuration:0.5 animations:^{
//消失时候的事件
}];
}];