首先說明兩種可以讓鍵盤隱藏的Method:
1、[view endEditing:YES] 這個方法可以讓整個view取消第一響應者,從而讓所有控件的鍵盤隱藏。
2、[textFiled resignFirstResponder] 這個則是比較常用的讓某個textFiled的鍵盤隱藏。
接下來就是幾種實現方式:
第一種: 使用view的touchesBegan:觸摸事件來實現對鍵盤的隱藏,當點擊view的區域就會觸發這個事件
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[textFiled resignFirstResponder];
}
第二種:創建自定義的觸摸手勢來實現對鍵盤的隱藏:
- (void)viewDidLoad
{
[super viewDidLoad];
UITap *tap = [[UITap alloc] initWithTarget:self action:@selector(keyboardHide:)];
//設置成NO表示當前控件響應後會傳播到其他控件上,默認爲YES。
tap.cancelsTouchesInView = NO;
//將觸摸事件添加到當前view
[self.view addGestureRecognizer:tapGestureRecognizer];
}
-(void)keyboardHide:(UITap*)tap{
[textFiled resignFirstResponder];
}
第三種:修改xib中UIView的Custom class爲UIControl,UIControl是一些常用控件如UIButton的父類,是UIView的派生類,實現了對觸摸和下按的封裝。
1、首先設置xib中得UIView的Custom class爲UIControl
2、設置關係事件,將xib中得UIView拖到.h區中
設置好事件爲Touch Up Inside
3、編寫隱藏代碼:
- (IBAction)touchView:(id)sender {
[self.view endEditing:YES];
}