Hiding the keyboard when a UITextField loses focus

I saw some topics on how to reject the keyboard when a UITextField loses focus, but it didn’t work for me, and I don’t know how to do it. "TouchhesBegan: withEvent:" in the following code is never called. Why?

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

    UITouch *touch = [[event allTouches] anyObject];
    if ([self.textFieldOnFocus isFirstResponder] && [touch view] != self.textFieldOnFocus) {
        [textFieldOnFocus resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

PS: This code has been pasted into a view controller that has a UITableView. UITextField is in the cell from this table.

So my opinion is this: this method is not called, because the touch happens on a UITableView from my ViewController. So, I think that I will have to subclass UITableView to use this method, as I saw on other Threads, but it might be easier.

could you help me? Many thanks!

+3
3

, delegate UITextField First Responder IB. () UIButton IBAction, . :

- (IBAction)hideKeyboard {
    [someTextField resignFirstResponder];
}

UIButton.

+2

, SO: tap View, "" UITextField.

-(void)handleViewTapGesture:(UITapGestureRecognizer *)gesture
{
    [self endEditing:YES];
}

ViewController. View:

-(void) setLoginView:(LoginView *)loginView
{
    _loginView = loginView;

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self.loginView action:@selector(handleTapGesture:)];    

    [tapRecognizer setDelegate:self];  // self implements the UIGestureRecognizerDelegate protocol

    [self.loginView addGestureRecognizer:tapRecognizer];    
}

. , . Apple - .

, , , , , UIGestureRecognizerDelegate :

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{    
    if ([touch.view isKindOfClass:[UIButton class]])    // Customize appropriately.
        return NO; // Don't let the custom gestureRecognizer handle the touch   

    return YES;
}
+2
-(void)touchesEnded: (NSSet *)touches withEvent: (UIEvent *)event
 {
    for (UIView* view in self.view.subviews) 
    {
        if ([view isKindOfClass:[UITextField class]])
        [view resignFirstResponder];
    }
}
0
source

Source: https://habr.com/ru/post/1756641/


All Articles