歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iPhone-使用TextField及鍵盤(useing TextField for inputs、using the keyboard)

iPhone-使用TextField及鍵盤(useing TextField for inputs、using the keyboard)

日期:2017/3/1 10:23:59   编辑:Linux編程

創建項目,名字為KeyBoard,我用的是xcode4.2!

在MainStoryboard.storyboard文件裡拖四個label和四個TextField,如下界面:

填滿內容:

點擊完成Done鍵盤會消失!!

首先我先說說四個TextField的屬性分別對應如下:

name:

age:keyboard改成Numbers and Punctuation

password:把Secure屬性勾上

email:keyBoard發成E-mail Address

接下來是在KeyboardViewController.h文件定義如下:

  1. - (IBAction)doneEdit:(id)sender;
在KeyboardViewController.m文件實現如下:
  1. - (IBAction)doneEdit:(id)sender {
  2. [sender resignFirstResponder];
  3. }
把四個TextFiled的Did​ End​ on​ Exit做連接出口IBAction,連到doneEdit方法上!這個大家都知道怎麼連哈!在此不給出圖例了!
[sender resignFirstResponder],是要求文本字段第一響應者的地位辭職,這就意味著不再需要鍵盤與文本字段的交互了,使其隱藏!

這樣,效果就達到了,還有人會想:“我不想按Done鍵使其隱藏,我想使它按下後面的背景就把鍵盤隱藏了。”,不要急,接下來就說這種情況!!!!

還在原來的項目中進行,在視圖中添加一個按鈕,一個很大的按鈕,能把正個視圖蓋住,把Type屬性改成Custom,並把按鈕拉到所有控件的上面,也就是第一位置如下圖,這樣做是為了不讓按鈕擋住所有按鈕!



在KeyboardViewController.h文件中添加代碼如下:

  1. @interface KeyboardViewController : UIViewController{
  2. UITextField *email;
  3. UITextField *password;
  4. UITextField *age;
  5. UITextField *name;
  6. }
  7. @property (retain, nonatomic) IBOutlet UITextField *email;
  8. @property (retain, nonatomic) IBOutlet UITextField *password;
  9. @property (retain, nonatomic) IBOutlet UITextField *age;
  10. @property (retain, nonatomic) IBOutlet UITextField *name;
  11. - (IBAction)buttonEdit:(id)sender;
  12. - (IBAction)doneEdit:(id)sender;
  13. @end
並把button按鈕Touch Up Inside事件連接到buttonEdit;

在KeyboardViewController.m文件實現:

  1. @synthesize email;
  2. @synthesize password;
  3. @synthesize age;
  4. @synthesize name;
  5. - (IBAction)buttonEdit:(id)sender {
  6. [email resignFirstResponder];
  7. [password resignFirstResponder];
  8. [age resignFirstResponder];
  9. [name resignFirstResponder];
  10. }

這樣就實現了點擊背影就關閉鍵盤了。

還有人會想:“我想一打開應用就打開鍵盤並且光標在name框內”。

那麼就在viewDidLoad 裡寫入代碼:

  1. - (void)viewDidLoad
  2. {
  3. [name becomeFirstResponder];
  4. [super viewDidLoad];
  5. }
嗯!

學習過程 中不怕麻煩,希望跟大家一塊努力學習!有什麼不好的地方,請多指出!!!

Copyright © Linux教程網 All Rights Reserved