键盘基本处理

最近碰到一些关于键盘处理的问题 特地将这些问题整理出来 以后遇到新的问题再继续完善...

  • 退出键盘的方式
    • 让textField不成为第一响应者
[self.textField resignFirstResponder];
  • 退出编辑模式
[self.view endEditing:YES];
  • 让textField的位置随键盘改变而改变
    • 可以通过通知实现
-(void)viewDidLoad{
[super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
  -(void)keyboardWillChange:(NSNotification *)note
{
    // 获得键盘的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 修改底部约束
    self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;
    //  执行动画
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
-(void)dealloc{ 
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

在实际开发中会遇到更多其他关于键盘处理的问题 在这里跟大家推荐一款好用的框架 IQKeyBoardManager

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容