How to hide the keyboard when I press return key in a UITextField?

前端 未结 12 1412
野趣味
野趣味 2020-12-04 07:31

Clicking in a textfield makes the keyboard appear. How do I hide it when the user presses the return key?

相关标签:
12条回答
  • 2020-12-04 07:49

    Try this,

    [textField setDelegate: self];
    

    Then, in textField delegate method

    - (BOOL)textFieldShouldReturn:(UITextField *)textField {
        [textField resignFirstResponder];
        return YES;
    }
    
    0 讨论(0)
  • 2020-12-04 07:52

    Define this class and then set your text field to use the class and this automates the whole hiding keyboard when return is pressed automatically.

    class TextFieldWithReturn: UITextField, UITextFieldDelegate
    {
    
        required init?(coder aDecoder: NSCoder) 
        {
            super.init(coder: aDecoder)
            self.delegate = self
        }
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool
        {
            textField.resignFirstResponder()
            return true
        }
    
    }
    

    Then all you need to do in the storyboard is set the fields to use the class:

    0 讨论(0)
  • 2020-12-04 07:55

    In viewDidLoad declare:

    [yourTextField setDelegate:self];

    Then, include the override of the delegate method:

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
    {
        [textField resignFirstResponder];
        return YES;
    }
    
    0 讨论(0)
  • 2020-12-04 07:56

    Swift 4

    Set delegate of UITextField in view controller, field.delegate = self, and then:

    extension ViewController: UITextFieldDelegate {
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            // don't force `endEditing` if you want to be asked for resigning
            // also return real flow value, not strict, like: true / false
            return textField.endEditing(false)
        }
    }
    
    0 讨论(0)
  • 2020-12-04 07:59

    If you want to hide the keyboard for a particular keyboard use [self.view resignFirstResponder]; If you want to hide any keyboard from view use [self.view endEditing:true];

    0 讨论(0)
  • 2020-12-04 08:01

    First make your file delegate for UITextField

    @interface MYLoginViewController () <UITextFieldDelegate>
    
    @end
    

    Then add this method to your code.

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

    Also add self.textField.delegate = self;

    0 讨论(0)
提交回复
热议问题