網頁

2013年2月25日 星期一

UITextField 與 keyboard 的互動


[iphone app 開發]

當user 點了UI上的 TextField 時,便會自動跳出鍵盤如下。




不過,build完之後,會發現,你點擊textField 鍵盤是跳出來了沒錯,但是縮不回去了。

也就是說,



1.我們需要讓user 有個地方可以按,去取消鍵盤,讓鍵盤消失。
=>到UI的TextField 右邊的return key 選項中,改成done。此外,由於你是在UITextField
這個UI元件的右邊找到這個設定,表示,到時候那個done被按下去時,是UITextField這個元件會負責送出done的動作。




2.在code 裡加一段負責handle 收到done 後,要取消鍵盤的行為。

你知道應該需要加一個IBAction 來處理done 吧
.h 中加入

-(IBAction)textFieldDone:(id)sender;


,m 中

-(IBAction)textFieldDone:(id)sender{


    [sender resignFirstResponder];

}


這裡的sender 就是 UITextField,它就是送出 done 的人。
而我們用它的 resignFirstResponder 是要跟sender 說,現在你可以釋放焦點了。

(當一些很明顯的焦點出現時,ios 會賦予它成為FirstResponder, 譬如user 正要輸入文字等
,而對於UITextField來說,當他成為FirstResponder 的第一個動作就是show 出鍵盤,這也是為什麼我們一行code都不用加,鍵盤就會自己跳出來的原因了。)


apple doc
UITextField Class Reference
........

Managing the Keyboard
When the user taps in a text field, that text field becomes the first responder and automatically asks the system to display the associated keyboard.



3. 最後,一樣去UI上把UITextField按右鍵,連上 "Did End on Exit" 和 textFieldDone 就ok啦。



至於,如何取得UI上user輸入的字串呢?
去查一下apple doc


UITextField Class Reference
Tasks
Accessing the Text Attributes
  •   text  property
  •   attributedText  property
  •   placeholder  property
  •   attributedPlaceholder  property
  •   font  property
  •   textColor  property
  •   textAlignment  property
  •   typingAttributes  propert
其中第一個text 在進去看

text
The text displayed by the text field.
@property(nonatomic, copy) NSString *text
Discussion
This string is nil by default.

就是user 填入的資訊摟。

.h 
    UITextField *textField_;
@property (nonatomic, retain) IBOutlet UITextField *textField;

.m
@synthesize textField  = textField_;


NSLog(@"%@",textField_.text);

就拿到了












沒有留言:

張貼留言