使用者按下返回按鈕時關閉鍵盤

設定檢視控制器以管理文字欄位的文字編輯。

class MyViewController: UITextFieldDelegate {

    override viewDidLoad() {
        super.viewDidLoad()
        
        textField.delegate = self
    }

}

每次按下鍵盤上的返回按鈕時都會呼叫 textFieldShouldReturn

迅速:

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()    
    return true;
}

Objective-C 的:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   [textField resignFirstResponder];
   return true;
}