Just My Life & My Work

設計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

參考:UITextField: 按下鍵盤上的return後,讓鍵盤消失收起虛擬鍵盤的各種方法

Comments on: "[iOS] UITextField 輸入完成讓鍵盤消失" (2)

  1. 未知 的大頭貼

    […] 我們已經知道如何讓TextField輸入完成讓鍵盤消失,現在想要使TextView 縮回虛擬鍵盤,可以怎麼做呢? […]

  2. 未知 的大頭貼

    […] 為了方便使用者輸入完之後跳至下一個欄位,Text Field當然可以實作出如此的功能!那我們可以怎麼做呢?可以先參考我上篇文章UITextField 輸入完成讓鍵盤消失。 […]

隨意留個言吧:)~

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料

標籤雲