简体   繁体   中英

Control-drag to create IBAction in Xcode 5 to dismiss keyboard?

I have a view controller with a text field. I'm trying to create an IBAction to dismiss they keyboard when user taps outside the text field by control-dragging from outside the text field in the Xib file to my .h file, but I don't get the option to choose "Action," only "Outlet" and "Outlet collection." I don't even get a window that asks me to choose when I control drag inside a *.m file. What am I missing?

I was able to do this in Xcode 4.

When you ctrl-drag from "outside the text field", you are most likely interacting with the top-level view of the view controller. This is a UIView object which does not have actions. Only views that inherit from UIControl have actions, eg buttons, text fields. This is not an XCode 4 vs 5 issue -- it's always been this way.

In your view controller, override touchesBegan:withEvent: . Make a call to [self.view endEditing] to dismiss the keyboard.

This is possible because your view controller inherits from the UIResponder class, as do UIViews . When the user touches something on the screen, the event gets passed up the responder chain, eg from subview to parent view to parent view controller etc., until one of those responders decides to respond to or purposefully discard that event. By overriding touchesBegan:withEvent: , your view controller can handle that event and do something meaningful (like dismiss the keyboard).

A simple solution would be using a simple UITapGestureRecognizer added to the "main" view.

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

Then the method hideKeyboard:

- (void)hideKeyboard
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
} <br>

The tap is sent through views until it finds one that could manage it, like the view controller view that triggers the gesture.

Use this code on your .m file

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

        selectedTextField = textField;
        return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        [selectedTextField resignFirstResponder];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM