iphone 怎么样才能方便的隐藏键盘
键盘的显示很方便,但是键盘比较方便的隐藏就不是那么容易了。
呼出了键盘后,可以在键盘的右边添加一个按钮,如果用户想隐藏键盘,就点此按钮,
就可以了。
但是在 IOS5 的情况下,中文输入法在键盘右边的按钮就会被选词区遮盖了。
隐藏键盘的按钮被系统的选词区遮盖了,基于这个状况,希望用户能够点击键盘区域以
外的地方也能隐藏键盘。
所以如何知道用户点击键盘以为区域就显得很重要了 由于在
ViewController 中 不 能 捕 获 以 下 Touch 事 件 , 以 下 Touch 主 要 是 针 对 UIView 的 -
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
所以我们无法通过
Touches 来判读用户是否点击了键盘以外区域,所以我选择了
UITapGestureRecognizer,通过捕获用户的 tap 事件,来隐藏键盘。在 ViewDidLoad 里添加如
下的方法:
1
-(void)addTapGuesture
2
{
3
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(hideKeyBoard:)];
4
[tapGesture setNumberOfTapsRequired:1];
5
[self.view addGestureRecognizer:tapGesture];
6
[tapGesture release];
7
}
我以为一切运行良好,可惜实际的情况并不是那么理想,比如画面 1 中有 UISwitch 和
UIButton, UITapGestureRecognizer 会隐藏了 UISwitch 和 UIButton 等一切能响应用户 Tap 的
控件。
还好 UITapGestureRecognizer 有过滤功能,它能够让你选择哪些控件需要响应
UITapGestureRecognizer 哪 些 不 需 要 实 现 UIGestureRecognizerDelegate 委 托 的 如 下 方 法 ,
YES 是需要响应,NO 为不需要响应
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:
(UITouch *)touch
8
{
9
10 if ([touch.view isKindOfClass:[CustomUISwitch class]] || [touch.view isKindOfClass: