超級好用呢
IOS7 點擊空白處隱藏鍵盤的幾種方法
IOS開發中經常要用到輸入框,默認情況下點擊輸入框就會彈出鍵盤,但是必須要實現輸入框return的委託方法才能取消鍵盤的顯示,對於用戶體驗來說很不友好,我們可以實現點擊鍵盤以外的空白區域來將鍵盤隱藏,以下我總結出了幾種隱藏鍵盤的方法:
首先說明兩種可以讓鍵盤隱藏的Method:
1、[viewendEditing:YES] 這個方法可以讓整個view取消第一響應者,從而讓所有控件的鍵盤隱藏。
2、[textFiled resignFirstResponder] 這個則是比較常用的讓某個textFiled的鍵盤隱藏。
接下來就是幾種實現方式:
第一種: 使用view的touchesBegan:觸摸事件來實現對鍵盤的隱藏,當點擊view的區域就會觸發這個事件
- -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
- [textFiled resignFirstResponder];
- }
或者
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[[UIApplication sharedApplication].keyWindow endEditing:YES];//或者改成[self.view endEditing:YES];
}
第二種:創建自定義的觸摸手勢來實現對鍵盤的隱藏:
- - (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];
- }
1、首先設置xib中得UIView的Custom class爲UIControl
2、設置關係事件,將xib中得UIView拖到.h區中
設置好事件爲Touch
Up Inside
3、編寫隱藏代碼:
- - (IBAction)touchView:(id)sender {
- [self.view endEditing:YES];
- }
好了,以上是三種比較常用的隱藏鍵盤的方法,每種都可以用於不同的場合和它的利與弊,就看如何運用了。
//轉自http://blog.csdn.net/swingpyzf/article/details/17091567