How to make return key on iPhone make keyboard disappear?

后端 未结 14 455
有刺的猬
有刺的猬 2020-12-02 07:06

I have two UITextFields (e.g. username and password) but I cannot get rid of the keyboard when pressing the return key on the keyboard. How can I do this?

相关标签:
14条回答
  • 2020-12-02 07:55

    First you need to conform to the UITextFieldDelegate Protocol in your View/ViewController's header file like this:

    @interface YourViewController : UIViewController <UITextFieldDelegate>
    

    Then in your .m file you need to implement the following UITextFieldDelegate protocol method:

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

    [textField resignFirstResponder]; makes sure the keyboard is dismissed.

    Make sure you're setting your view/viewcontroller to be the UITextField's delegate after you init the textfield in the .m:

    yourTextField = [[UITextField alloc] initWithFrame:yourFrame];
    //....
    //....
    //Setting the textField's properties
    //....    
    //The next line is important!!
    yourTextField.delegate = self; //self references the viewcontroller or view your textField is on
    
    0 讨论(0)
  • 2020-12-02 07:55

    Add this instead of the pre-defined class

    class ViewController: UIViewController, UITextFieldDelegate {
    

    To remove keyboard when clicked outside the keyboard

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            self.view.endEditing(true)
        }
    

    and to remove keyboard when pressed enter

    add this line in viewDidLoad()

    inputField is the name of the textField used.

    self.inputField.delegate = self
    

    and add this function

    func textFieldShouldReturn(textField: UITextField) -> Bool {        
            textField.resignFirstResponder()        
            return true        
        }
    
    0 讨论(0)
提交回复
热议问题