iOS开发之键盘出现和收起

🌟键盘相关通知

键盘状态改变的时侯系统会发出一些待定的通知

    // 键盘即将显示
    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];
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值