Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear button at uisearchbar not working at all

I created a search bar programmatically and added to my view using the codes below:

- (void)viewDidLoad
{
    searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(xPositionForSearchBar, yPositionForSearchBar, widthForSearchBar, heightForSearchBar)];
        UIView *bg = [[searchBar subviews] objectAtIndex:0];
        searchBar.delegate = self;
        searchBar.placeholder = @"Search record";
        for(UIView *view in searchBar.subviews){
            if([view isKindOfClass:[UITextField class]]){
                UITextField *tf = (UITextField *)view;
                tf.delegate = self;
                break;
            }
        }
        [bg removeFromSuperview];
        [self.view addSubview: searchBar];
}

The code is implemented with UISearchBarDelegate and UITextFieldDelegate.

I have tried using

- (void)searchBarCancelButtonClicked:(UISearchBar *)aSearchBar
{
    NSLog(@"cancel clicked");
    searchBar.text = @"";
    [aSearchBar resignFirstResponder];
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    NSLog(@"clear");
    [self performSelector:@selector(searchBarCancelButtonClicked:) withObject:searchBar afterDelay: 0.1];
    return YES;
}

and yet, the text inside the searchBar is not cleared at all when i click on the "clear button" - a circle with a "X" inside.

The clear button works when I implemented it in IB. Wonder why?

Kindly advice, many thanks.

like image 363
kevin.ng Avatar asked Sep 06 '12 03:09

kevin.ng


1 Answers

This might happen if you position your search bar out of the bounds of a parent view. Then, the touches aren't delivered to your searchBar properly. This also affects text editing controls like copy & paste.

like image 108
Ortwin Gentz Avatar answered Oct 23 '22 06:10

Ortwin Gentz