設計UITextField遇到一個問題,就是使用者在Text Field輸入完畢之後,鍵盤無法如期消失,想要設定按下Enter讓它消失該怎麼做呢?目前我知道有兩種方法~
方法一:用程式產生的Text Field可以自行寫方法,利用target-action的目標行為設定:
-(void)textFieldDone:(UITextField*)textField
{
[textField resignFirstResponder];
}
[textField addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
方法二:若使用Interface Builder建立Text Field,必須遵從UITextFieldDelegate協定,且拉藍線到File’s Owner跟delegate產生關係,便可實作SDK裡的方法:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Xcode裡的解釋:
textFieldShouldReturn:
Asks the delegate if the text field should process the pressing of the return button.
– (BOOL)textFieldShouldReturn:(UITextField *)textField
Parameters
textField
The text field whose return button was pressed.
Return Value
YES if the text field should implement its default behavior for the return button; otherwise, NO.
Discussion
The text field calls this method whenever the user taps the return button. You can use this method to implement any custom behavior when the button is tapped.
Availability
Available in iOS 2.0 and later.
Declared In
UITextField.h
resignFirstResponder
Notifies the receiver that it has been asked to relinquish its status as first responder in its window.
– (BOOL)resignFirstResponder
Discussion
The default implementation returns YES, resigning first responder status. Subclasses can override this method to update state or perform some action such as unhighlighting the selection, or to return NO, refusing to relinquish first responder status. If you override this method, you must call super (the superclass implementation) at some point in your code.
Availability
Available in iOS 2.0 and later.
See Also
– isFirstResponder
– canResignFirstResponder
Declared In
UIResponder.h
Comments on: "[iOS] UITextField 輸入完成讓鍵盤消失" (2)
[…] 我們已經知道如何讓TextField輸入完成讓鍵盤消失,現在想要使TextView 縮回虛擬鍵盤,可以怎麼做呢? […]
讚讚
[…] 為了方便使用者輸入完之後跳至下一個欄位,Text Field當然可以實作出如此的功能!那我們可以怎麼做呢?可以先參考我上篇文章UITextField 輸入完成讓鍵盤消失。 […]
讚讚