創建項目,名字為KeyBoard,我用的是xcode4.2!
在MainStoryboard.storyboard文件裡拖四個label和四個TextField,如下界面:
填滿內容:
點擊完成Done鍵盤會消失!!
首先我先說說四個TextField的屬性分別對應如下:
name:
age:keyboard改成Numbers and Punctuation
password:把Secure屬性勾上 www.2cto.com
email:keyBoard發成E-mail Address
接下來是在KeyboardViewController.h文件定義如下:
<span style="font-size:16px;">- (IBAction)doneEdit:(id)sender;</span>
<span style="font-size:16px;">- (IBAction)doneEdit:(id)sender;</span>在KeyboardViewController.m文件實現如下:
[html] <span style="font-size:16px;">- (IBAction)doneEdit:(id)sender {
[sender resignFirstResponder];
}</span>
<span style="font-size:16px;">- (IBAction)doneEdit:(id)sender {
[sender resignFirstResponder];
}</span>
把四個TextFiled的Did End on Exit做連接出口IBAction,連到doneEdit方法上!這個大家都知道怎麼連哈!在此不給出圖例了!
[sender resignFirstResponder],是要求文本字段第一響應者的地位辭職,這就意味著不再需要鍵盤與文本字段的交互了,使其隱藏!
這樣,效果就達到了,還有人會想:“我不想按Done鍵使其隱藏,我想使它按下後面的背景就把鍵盤隱藏了。”,不要急,接下來就說這種情況!!!!
還在原來的項目中進行,在視圖中添加一個按鈕,一個很大的按鈕,能把正個視圖蓋住,把Type屬性改成Custom,並把按鈕拉到所有控件的上面,也就是第一位置如下圖,這樣做是為了不讓按鈕擋住所有按鈕!
在KeyboardViewController.h文件中添加代碼如下:
[cpp] @interface KeyboardViewController : UIViewController{
UITextField *email;
UITextField *password;
UITextField *age;
UITextField *name;
}
@property (retain, nonatomic) IBOutlet UITextField *email;
@property (retain, nonatomic) IBOutlet UITextField *password;
@property (retain, nonatomic) IBOutlet UITextField *age;
@property (retain, nonatomic) IBOutlet UITextField *name;
- (IBAction)buttonEdit:(id)sender;
- (IBAction)doneEdit:(id)sender;
@end
@interface KeyboardViewController : UIViewController{
UITextField *email;
UITextField *password;
UITextField *age;
UITextField *name;
}
@property (retain, nonatomic) IBOutlet UITextField *email;
@property (retain, nonatomic) IBOutlet UITextField *password;
@property (retain, nonatomic) IBOutlet UITextField *age;
@property (retain, nonatomic) IBOutlet UITextField *name;
- (IBAction)buttonEdit:(id)sender;
- (IBAction)doneEdit:(id)sender;
@end
並把button按鈕Touch Up Inside事件連接到buttonEdit;
在KeyboardViewController.m文件實現:
[cpp] @synthesize email;
@synthesize password;
@synthesize age;
@synthesize name;
- (IBAction)buttonEdit:(id)sender {
[email resignFirstResponder];
[password resignFirstResponder];
[age resignFirstResponder];
[name resignFirstResponder];
}
@synthesize email;
@synthesize password;
@synthesize age;
@synthesize name;
- (IBAction)buttonEdit:(id)sender {
[email resignFirstResponder];
[password resignFirstResponder];
[age resignFirstResponder];
[name resignFirstResponder];
}
這樣就實現了點擊背影就關閉鍵盤了。
還有人會想:“我想一打開應用就打開鍵盤並且光標在name框內”。
那麼就在viewDidLoad 裡寫入代碼:
[cpp] - (void)viewDidLoad
{
[name becomeFirstResponder];
[super viewDidLoad];
}
- (void)viewDidLoad
{
[name becomeFirstResponder];
[super viewDidLoad];
}
嗯!
學習過程 中不怕麻煩,希望跟大家一塊努力學習!有什麼不好的地方,請多指出!!!
摘自 任海麗(3G/移動開發)