第一種: 使用view的touchesBegan:觸摸事件來實現對鍵盤的隱藏,當點擊view的區域就會觸發這個事件
[html] view plaincopyprint?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[textFiled resignFirstResponder];
}
第二種:創建自定義的觸摸手勢來實現對鍵盤的隱藏:
[html] view plaincopyprint?
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
//設置成NO表示當前控件響應後會傳播到其他控件上,默認爲YES。
tapGestureRecognizer.cancelsTouchesInView = NO;
//將觸摸事件添加到當前view
[self.view addGestureRecognizer:tapGestureRecognizer];
}
-(void)keyboardHide:(UITapGestureRecognizer*)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、編寫隱藏代碼:
[html] view plaincopyprint?
- (IBAction)touchView:(id)sender {
[self.view endEditing:YES];
}
好了,以上是三種比較常用的隱藏鍵盤的方法,每種都可以用於不同的場合和它的利與弊,就看如何運用了。