How to cancel a text box as the first responder in uitableviewcell

I use this code to cancel mine UITextFieldas firstResponderif using standard UIView.

But now I have it UITextFieldin my UITableViewCellin UITableView, and the code does not remove the text field as the first responder when I click outside the text field. Any ideas how to make this work?

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

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

enter image description here

+5
source share
2 answers

[[self tableView] endEditing:YES]; - my standard approach.

+13
source

UITableView, , , : : UITableView. , TapGestureRecognizer, - scrollViewWillBeginDragging: UIScrollViewDelegate. , :

   /**
     *  Shortcut for resigning all responders and pull-back the keyboard
     */
    -(void)hideKeyboard
    {
        //this convenience method on UITableView sends a nested message to all subviews, and they resign responders if they have hold of the keyboard
        [self.tableView endEditing:YES];

    }

textField UITableView, , .

Tap :

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupKeyboardDismissGestures];

}

- (void)setupKeyboardDismissGestures
{

//    Example for a swipe gesture recognizer. it was not set-up since we use scrollViewDelegate for dissmin-on-swiping, but it could be useful to keep in mind for views that do not inherit from UIScrollView
//    UISwipeGestureRecognizer *swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
//    swipeUpGestureRecognizer.cancelsTouchesInView = NO;
//    swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
//    [self.tableView addGestureRecognizer:swipeUpGestureRecognizer];

    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    //this prevents the gestureRecognizer to override other Taps, such as Cell Selection
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];

}

tapGestureRecognizer.cancelsTouchesInView to NO - , gesureRecognizer UITableView (, ).

, / UITableView, UIScrollViewDelegate scrollViewWillBeginDragging: method, :

.h

@interface MyViewController : UIViewController <UIScrollViewDelegate>

.m file

#pragma mark - UIScrollViewDelegate

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hideKeyboard];
}

, ! =)

+1

All Articles