How do I dismiss the iOS keyboard?

后端 未结 16 1012
情书的邮戳
情书的邮戳 2020-11-29 20:00

I have a UITextfield that i\'d like to dismiss the keyboard for. I can\'t seem to make the keyboard go away no matter what code i use.

相关标签:
16条回答
  • 2020-11-29 20:06

    To resign any text field in the app

    UIApplication.shared.keyWindow?.endEditing(true)
    

    This approach is clean and guarantied to work because the keyWindow is, by definition, the root view of all possible views displaying a keyboard (source):

    The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.

    0 讨论(0)
  • 2020-11-29 20:07
    -(void)textFieldDidBeginEditing:(UITextField *)textField
    {
        // your code
    
        [textField reloadInputViews];
    }
    
    0 讨论(0)
  • 2020-11-29 20:08

    In your view controller YourViewController.h file, make sure you implement UITextFieldDelegate protocol :

    @interface YourViewController : <UITextFieldDelegate>
    
    @end
    

    Then, in YourViewController.m file, implement the following instance method:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [self.yourTextField1 resignFirstResponder];
        [self.yourTextField2 resignFirstResponder];
        ...
        [self.yourTextFieldn resignFirstResponder];
    }
    
    0 讨论(0)
  • 2020-11-29 20:08

    as a last resort

    0 讨论(0)
  • 2020-11-29 20:09
    [myTextField resignFirstResponder]
    

    Here, second paragraph in the Showing and Hiding the Keyboard section.

    0 讨论(0)
  • 2020-11-29 20:09

    You just replace yourTextFieldName with, you guessed it! your textfield. This will close the keyboard.

    [yourTextFieldName resignFirstResponder];
    
    0 讨论(0)
提交回复
热议问题