0

I have declared in my header file this:

UITapGestureRecognizer* tap;

And on viewDidLoad:

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

    tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                  action:@selector(hideKeyboard)];
    tap.enabled = NO;
    [self.view addGestureRecognizer:tap];
}

I've added UITextFieldDelegate, and added this:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    tap.enabled = YES;

    return YES;
}

If I touches anywhere outside the keyboard, it disappears, but if I touch in a UIButton it doesn't disappear.

Do you know why?

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • Take a look at [this](http://stackoverflow.com/questions/3344341/uibutton-inside-a-view-that-has-a-uitapgesturerecognizer) – luiso1979 Sep 30 '13 at 08:32

3 Answers3

0

The UIButton intercepts and handles the touch (not propagating it). One option would be to set your view controller as the gesture recognizer delegate and implement the method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

But in your case i think it would be enough to dismiss the keyboard in the method that fires when the button is pressed.

micantox
  • 5,446
  • 2
  • 23
  • 27
0
 UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGestureRecognizer.delegate = self;
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tapGestureRecognizer];


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {


    if (touch.view == self.button) {//change it to your condition UIButton
        return NO;
    }
    return YES;
}

-(void)dismissKeyboard
{
    [self.textField resignFirstResponder];
}
karthika
  • 4,085
  • 3
  • 21
  • 23
0

Add a target-action pairing for when the user touches down on the button:

[button addTarget:self
           action:@selector(dismissKeyboard)
 forControlEvents:UIControlEventTouchDown];
Guy Kogus
  • 7,251
  • 1
  • 27
  • 32