Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISearchBar delegate not responding to cancel button

I have a UIViewController that is a UISearchBarDelegate and a MKMapViewDelegate. The searchBarSearchButtonClicked event works fine, but when testing in iOS 4.2 the searchBarCancelButtonClicked never gets called when hitting the cancel button. In 4.3 everything works fine. I have other views with identical code and it works fine. I have triple checked the method signatures.

Could it be something to do with the MapView, or am I doing something blatantly wrong?

My .h file:

@interface MyViewController : UIViewController <UISearchBarDelegate,MKMapViewDelegate,UIAlertViewDelegate>{
MKMapView *mapMainView;
UISearchBar *sBar;

}

@property (nonatomic, retain) UISearchBar *sBar;
@end

And I create the search bar like so:

sBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320.0, 70.0)] autorelease];
sBar.delegate = self;
sBar.showsCancelButton = YES;
[self.view addSubview:sBar];
[sBar becomeFirstResponder];

The method:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
searchBar.hidden = YES;
}

Does anyone have an idea of why this may be happening?

like image 805
user213517 Avatar asked May 14 '11 19:05

user213517


2 Answers

I had the exact same problem. Holding the cancel button for a few seconds worked.

The reason for me was that I had implemented UITapGestureRecognizer in the tableview. So this took precedence over the button click or 'x' button click in the search bar.

The solution in my case was to restrict the gesture recognition to only the backgroundview of the tableview. I guess similar thing might be happening in your case. Try to restrict the gesture recognizers to the minimum subview required and the search bar should be outside that view.

like image 169
Anil Puttabuddhi Avatar answered Oct 02 '22 01:10

Anil Puttabuddhi


Probably your sbar object are releasing, in this case is an autorelease object, Why ?. Try declaring sBar as IBOutlet property. Make the apropiate links in the Interface Builder, remove the alloc as you code it, put in viewDidUnload self.sbar = nil; and releas it in dealloc. in viewDidLoad put this.

sBar.delegate = self;
sBar.showsCancelButton = YES; // this is an option in object inspector
[self.view addSubview:sBar];
[sBar becomeFirstResponder]; //remove this.

Tell me if it works

like image 42
bolek Avatar answered Oct 02 '22 02:10

bolek