Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextfield's clear button hides keyboard when its inside UIScrollView

I have a textfield inside a UIScrollView and i want to show a clear button when user starts editing. Also i need to hide keyboard when user taps the background of UIScrollview (but not the textfield). Displaying that clear button isn't a problem, the problem is that when clear button is tapped keyboard gets hidden and the text field doesn't get cleared. Obviously the problem is with the gesture recognizer, because method dealing with this gets fired when the clear button is clicked (but it's not fired when the text field is tapped). Here's my code :

    //adding gesture recognizer so i can hide keyboard when user taps scrollview
    - (void) textFieldDidBeginEditing:(UITextField *)textField
    {
        if (self.tapOutside == nil) self.tapOutside = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTouchOutSide:)];

        [self.scrollView addGestureRecognizer:self.tapOutside];
    }

    //This hides keyboard BUT IS ALSO CALLED WHEN CLEAR BUTTON IS TAPPED
    - (void)textFieldTouchOutSide:(id)sender
    {
        [self.textfield resignFirstResponder];
    }

    //NEVER GETS CALLED
    - (BOOL) textFieldShouldClear:(UITextField *)textField {
        return YES;
    }

Any ideas how to solve this? Maybe better way to add gesture recognizer? I can't think of no elegant solution ... Thanks a lot in advance...

like image 973
animal_chin Avatar asked Apr 12 '12 15:04

animal_chin


1 Answers

I had the same problem and solved it implementing the following method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    // Disallow recognition of gestures in unwanted elements
    if ([touch.view isMemberOfClass:[UIButton class]]) { // The "clear text" icon is a UIButton
        return NO;
    }
    return YES;
}

Don't forget to conform to the "UIGestureRecognizerDelegate" protocol and set the delegate (using your vars):

self.tapOutside.delegate = self;

Cheers

like image 66
jihonrado Avatar answered Sep 30 '22 15:09

jihonrado