How to resign first responder from text field when

2019-01-22 07:04发布

I have filled my view with ScrollView (same size as the view) and I'm stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any idea on how to do that ? I'm using the following method but it's not working as expected:

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

Thx for helping,

Stephane

17条回答
老娘就宠你
2楼-- · 2019-01-22 07:41

When possible the best option is to make your UIView to inherit from UIButton instead.

You just need to change it in Interface Builder and immediately you will get the options to create an Action "Touch Up Inside" like any other button.

Your view will work as usual because UIButton is still a view but you will get notified when someone taps on the view. There you can call

[self.view endEditing:YES];

To resign any keyboard.

Please note that if your view is an UIScrollView this solution is not for you.

查看更多
小情绪 Triste *
3楼-- · 2019-01-22 07:42

This is the easiest way iv found that works consistently. Just add a tap gesture recognizer on the view and you're good to go.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

[self.view endEditing:YES];

}

查看更多
Luminary・发光体
4楼-- · 2019-01-22 07:44

For Swift 3 and Swift 4 you can do this:

func viewDidLoad() {
    super.viewDidLoad()

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))

    self.view.addGestureRecognizer(tap)
}

@objc func hideKeyboardByTappingOutside() {
    self.view.endEditing(true)
}
查看更多
老娘就宠你
5楼-- · 2019-01-22 07:48

Just create an IBOutlet or pointer to the text field and call [textField resignFirstResponder]; from where ever you want.

查看更多
Animai°情兽
6楼-- · 2019-01-22 07:48

This is what I do...

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllKeyboards)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];

-(void) hideAllKeyboards {
    [textField_1 resignFirstResponder];
    [textField_2 resignFirstResponder];
    [textField_3 resignFirstResponder];
    .
    .
    .
    [textField_N resignFirstResponder];
}
查看更多
登录 后发表回答