UISearchBar delegate not responding to cancel button

痴心易碎 提交于 2019-12-05 12:49:00

问题


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?


回答1:


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.




回答2:


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




回答3:


try this:

sBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320.0, 70.0)];

sBar.delegate = self;

sBar.showsCancelButton = YES;

[self.view addSubview:sBar];

and try to put release in dealloc




回答4:


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        [self.searchDisplayController setActive:NO animated:YES];
        [self.searchDisplayController.searchBar resignFirstResponder];
    }
}


来源:https://stackoverflow.com/questions/6004438/uisearchbar-delegate-not-responding-to-cancel-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!