The cleanup button in uisearchbar does not work at all

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

- (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 using UISearchBarDelegate and UITextFieldDelegate.

I 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 does not clear at all when I click the "clear button" button - a circle with an "X" inside.

The cleanup button works when I implemented it in IB. I wonder why?

I ask for advice, thank you very much.

+6
source share
2 answers

This can happen if you place your search bar outside the boundaries of the parent view. Then, touches are not delivered to your search. It also affects text editing elements such as copy and paste.

+2
source

I checked your code, it works great on the device as well as on the simulator.

0
source

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


All Articles