在iOS开发中,我们经常处理这样的情况:
当键盘出现或者消失的时候,我们需要做一些相应的操作。比如键盘上面的工具条的位置变化等。
这里我们就假设有一个工具条在键盘的上面,我们要求当键盘出现的时候,工具条的位置向上移动始终在键盘的上面,当键盘消失的时候,工具条向下移动到屏幕的下面。
这时候,我们应该怎么处理呢?
是不是觉得思路很清晰了,那么开始吧。
1、给键盘设一个通知
/** * 给键盘的frame改变添加监听 * @param keyBoardWillChangeFrame: 监听方法 */[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
2、在键盘的通知监听方法里面做需要的操作
- (void)keyboardWillChangeFrame:(NSNotification *)notification{ // 键盘显示/隐藏完毕的frame CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 修改底部约束 self.bottomSapce.constant = XMGScreenH - frame.origin.y; // 动画时间 CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; // 动画 [UIView animateWithDuration:duration animations:^{ [self.view layoutIfNeeded]; }];}
上一段代码解释:
notification.userInfo:
self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keyboardF.size.height);
@PRoperty (readwrite, retain) UIView *inputView;
最后,一定要记得在dealoc方法里释放监听
- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self];}
有时候在同一个界面里面,可能有多个TextField输入框,而点击不同额输入框,我们可能希望弹出的键盘拥有不同的工具条,这时候我们怎么办呢?
//这里不贴图了,比较简单UIView *tool1 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar1" owner:nil options:nil] lastObject];UIView *tool2 = [[[NSBundle mainBundle] loadNibNamed:@"ToolBar2" owner:nil options:nil] lastObject];self.textField1.inputAccessoryView = tool1;self.textField2.inputAccessoryView = tool2;
成为第一响应者(可以调出键盘)
- (BOOL)becomeFirstResponder;
取消第一响应者
- (BOOL)resignFirstResponder;
全部取消第一响应者
- (BOOL)endEditing:(BOOL)force; //使用这个使得view或者其所有的子视图都取消第一响应者 (optionally force)
新闻热点
疑难解答