在使用 UITextField 時,往往需要在使用者輸入完成後隱藏軟鍵盤。要實現這一點,需要讓視圖的 Controller 遵循 UITextFieldDelegate 代理,並撰寫相應程式碼。
首先在介面中宣告 UITextField,並讓類別遵循 UITextFieldDelegate 協議:
#import <UIKit/UIKit.h>
@interface TestViewController : UIViewController <UITextFieldDelegate>
{
IBOutlet UITextField *txt;
}
@property (nonatomic, retain) UITextField *txt;
@end接著別忘了在 viewDidLoad 中指定文本框的代理,這一步非常關鍵,否則後續方法不會有反應:
- (void)viewDidLoad {
[super viewDidLoad];
txt.delegate = self;
}當使用者按下鍵盤的 Return 鍵時,透過 textFieldShouldReturn 方法讓文本框放棄第一響應者即可:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}當使用者點擊清除(那個小叉號)時也可一併隱藏鍵盤。此處若回傳 YES 反而無法隱藏,因此採取迂迴做法,回傳 NO 並清空文字:
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
[textField resignFirstResponder];
textField.text = @"";
return NO;
}若希望點擊視圖空白處時收起鍵盤,可重寫 touchesBegan 方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[txt resignFirstResponder];
}總結來說,設定代理是最關鍵的一步,只要記得指定 delegate,再搭配上述幾個方法,就能靈活控制軟鍵盤的顯示與隱藏。