🌟键盘相关通知
键盘状态改变的时侯系统会发出一些待定的通知
// 键盘即将显示
UIKeyboardWillShowNotification
// 键盘显示完毕
UIKeyboardDidShowNotification
// 键盘即将隐藏
UIKeyboardWillHideNotification
// 键盘隐藏完毕
UIKeyboardDidHideNotification
// 键盘的位置尺寸即将发生改变
UIKeyboardWil1ChangeFrameNotification
// 键盘的位置尺寸改变完毕
UIKeyboardDidChangeFrameNotification
键盘通知相关参数属性,具体使用参考下面的应用
// 键盘大小参数 CGRect
UIKeyboardFrameBeginUserInfoKey
UIKeyboardFrameEndUserInfoKey
// 键盘出现动画持续时间 double
UIKeyboardAnimationDurationUserInfoKey
// 键盘出现动画曲线(动画参数)NSUInteger
UIKeyboardAnimationCurveUserInfoKey
// 此键的值是一个NSNumber包含布尔值的对象,该值指示键盘是否属于当前应用程序。
// 通过iPadOS中的多任务处理,系统会在键盘出现和消失时通知所有可见的应用程序。
// 该值YES适用于导致键盘出现的应用程序和NO其他应用程序。
UIKeyboardIsLocalUserInfoKey
监听键盘通知相关应用
在添加键盘出现通知监听(在init
或者viewDidLoad
的时候),添加键盘消失通知监听(dealloc
),收到的通知中会带有键盘相关的参数属性
/// 添加通知
- (void)addNotification {
// 键盘通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
/// 移除通知
- (void)removeNotification {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
/// 键盘出现
- (void)keyboardWillShow:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
// 键盘大小参数CGRect
CGRect rect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 键盘出现动画持续时间
NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
// 动画调整相关页面
[UIView animateWithDuration:duration animations:^{
}];
}
/// 键盘收起
- (void)keyboardWillHide:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
// 键盘出现动画持续时间
NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
// 动画调整相关页面
[UIView animateWithDuration:duration animations:^{
}];
}
控制键盘收起
除了用户在键盘(原生键盘不支持,第三方部分有该功能)收回,还可以主动控制
- 🍊方法一:找到唤出键盘的对象,执行注销第一响应者(谁唤起谁收回)
// 第一响应者注销
[firstResponder resignFirstResponder];
- 🍊方法二:
UIViewController.view
,执行endEditing
停止编辑
[self.view endEditing:YES];
- 🍊方法三:在获取响应者或者控制器比较困难的情况下,直接执行
UIApplication
层面的方法,两个方法都可以
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];