iOS 键盘的隐藏

时间:2023-03-09 02:39:37
iOS 键盘的隐藏
 在 iOS开发中 最常用的 一些控件,如TextFiled 和 TextView,点击时会自动弹出键盘,但是隐藏操作需要我们自己来编码完成。
最常用的一种方法是,让TextFiled 和 TextView 放弃第一响应者的身份。关于控件的事件相应链这里不再多说了。
我们可以右击控件,关联一个 Edit did end exit 的 IBAction方法。在方法里面添加一句代码即可。这样,在完成键盘输入后,点击return键就会隐藏键盘了。
- (IBAction)TextFiledDidEndOnExit:(id)sender {
[sender resignFirstResponder];
}

当然我们的一个界面有时会有很多 键盘响应的控件。我们希望只需点击控件所在的背景(view或编辑区以外)就可以隐藏键盘。最常用的方法是:首先,我们先将view 的Custom Class设置为UIControl(在第三个检查器里).然后,给View关联一个 touch down(只有view 的自定义类属于 UIControl时才有该方法)的方法 - (IBAction)View_TouchDown:(id)sender;。最后,在方法里添加个个控件放弃第一响应者的身份的方法。[self.textFiled resignFirstResponder];[self.textView resignFirstResponder];

- (IBAction)View_TouchDown:(id)sender {
[self.TextFiled resignFirstResponder];
[self.TextView resignFirstResponder];
}

当然,也可以不改变自定义类为UIControl,还是使用Custom 为 UIView,请使用以下方法。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (![self.TextView isExclusiveTouch]) {
[self.TextView resignFirstResponder];
}
}

还有一种方法,就是用通知的方法。稍微麻烦点。