How to hide the keyboard when i press return key i

2019-01-12 18:05发布

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

10条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-12 18:33

Try this,

[textField setDelegate: self];

Then, in textField delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
查看更多
▲ chillily
3楼-- · 2019-01-12 18:34

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;

查看更多
男人必须洒脱
4楼-- · 2019-01-12 18:35
[textField resignFirstResponder];

Use this

查看更多
【Aperson】
5楼-- · 2019-01-12 18:37

In swift do like this:
First in your ViewController implement this UITextFieldDelegate For eg.

class MyViewController: UIViewController, UITextFieldDelegate {
....
}

Now add a delegate to a TextField in which you want to dismiss the keyboard when return is tapped either in viewDidLoad method like below or where you are initializing it. For eg.

override func viewDidLoad() {

    super.viewDidLoad()   
    myTextField.delegate = self
}

Now add this method.

func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    return true
}
查看更多
甜甜的少女心
6楼-- · 2019-01-12 18:43

In viewDidLoad declare:

[yourTextField setDelegate:self];

Then, include the override of the delegate method:

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
查看更多
再贱就再见
7楼-- · 2019-01-12 18:45

Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.

Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:

extension UIViewController : UITextFieldDelegate {
    ...
}

but the alternative works as well:

class MyViewController: UIViewController {
    ...
}

Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    return textField.endEditing(false)
}

In your viewDidLoad method, set the textfield's delegate to self

@IBOutlet weak var myTextField: UITextField!
...

override func viewDidLoad() {
    ..
    myTextField.delegte = self;
    ..
}

That should be all. Now, when you press return the textFieldShouldReturn should be called.

查看更多
登录 后发表回答