自動隱藏軟鍵盤,分為兩步,一個是單擊軟鍵盤外部任意空間;另外一個是單擊軟鍵盤上的return鍵。下面依次實現
單擊軟鍵盤外部空間鍵隱藏軟鍵盤:
一:在viewDidLoad中添加一個UITabGestureRecognizer,並將其添加到ViewController的view對象上
[cpp]
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
二:可以看到上面有一個dismissKeyboard的selector,下面實現該方法,並在方法中通過resignFirstResponder來隱藏軟鍵盤
[cpp]
-(void)dismissKeyboard {
[feedbackTextField resignFirstResponder];
}
單擊軟鍵盤上的return鍵隱藏軟鍵盤:
一:使ViewController實現UITextFieldDelegate協議,ViewController.h
[cpp]
//
// FeedBackViewController.h
// YofotoEdu
//
// Created by wly on 13-10-14.
// Copyright (c) 2013年 yofoto. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FeedBackViewController : UIViewController <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *feedbackTextField;
@end
二:在ViewDidLoad為UITextFiled指定delegate
[cpp]
feedbackTextField.delegate = self;
三:實現UITextFieldDelegate中的textFieldShouldReturn:方法
[cpp]
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[feedbackTextField resignFirstResponder];
}