IOS 點擊空白處隱藏鍵盤的幾種方法

第一種: 使用view的touchesBegan:觸摸事件來實現對鍵盤的隱藏,當點擊view的區域就會觸發這個事件

[html] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片

  1. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{  

  2.     [textFiled resignFirstResponder];  

  3. }  


第二種:創建自定義的觸摸手勢來實現對鍵盤的隱藏:

[html] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片

  1. - (void)viewDidLoad  

  2. {  

  3.     [super viewDidLoad];  

  4.     UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];  

  5.     //設置成NO表示當前控件響應後會傳播到其他控件上,默認爲YES。  

  6.     tapGestureRecognizer.cancelsTouchesInView = NO;  

  7.     //將觸摸事件添加到當前view  

  8.     [self.view addGestureRecognizer:tapGestureRecognizer];  

  9. }  

  10.   

  11. -(void)keyboardHide:(UITapGestureRecognizer*)tap{  

  12.     [textFiled resignFirstResponder];  

  13. }  


第三種:修改xib中UIView的Custom class爲UIControl,UIControl是一些常用控件如UIButton的父類,是UIView的派生類,實現了對觸摸和下按的封裝。

1、首先設置xib中得UIView的Custom class爲UIControl


2、設置關係事件,將xib中得UIView拖到.h區中

設置好事件爲Touch Up Inside

3、編寫隱藏代碼:

[html] view plaincopyprint?在CODE上查看代碼片派生到我的代碼片

  1. - (IBAction)touchView:(id)sender {  

  2.      [self.view endEditing:YES];  

  3. }  


好了,以上是三種比較常用的隱藏鍵盤的方法,每種都可以用於不同的場合和它的利與弊,就看如何運用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章