14

我有一个UIViewController是一个UISearchBarDelegate和一个MKMapViewDelegate。该searchBarSearchButtonClicked事件工作正常,但在 iOS 4.2 中进行测试时,当点击取消按钮时,searchBarCancelButtonClicked 永远不会被调用。在 4.3 中一切正常。我有其他具有相同代码的视图,它工作正常。我已经三次检查了方法签名。

这可能与 MapView 有关,还是我做错了什么?

我的 .h 文件:

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

}

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

我像这样创建搜索栏:

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

方法:

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

有谁知道为什么会发生这种情况?

4

4 回答 4

21

我有同样的问题。按住取消按钮几秒钟就可以了。

我的原因是我在 tableview 中实现了 UITapGestureRecognizer。因此,这优先于搜索栏中的按钮单击或“x”按钮单击。

在我的情况下,解决方案是将手势识别限制在表格视图的背景视图中。我想你的情况可能会发生类似的事情。尝试将手势识别器限制为所需的最小子视图,并且搜索栏应位于该视图之外。

于 2011-09-07T19:25:42.947 回答
4

可能您的 sbar 对象正在释放,在这种情况下是自动释放对象,为什么?尝试将 sBar 声明为 IBOutlet 属性。在 Interface Builder 中创建适当的链接,在编码时删除 alloc,放入 viewDidUnload self.sbar = nil; 并在 dealloc 中释放它。在 viewDidLoad 中放了这个。

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

告诉我它是否有效

于 2011-05-19T11:34:54.580 回答
1
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        [self.searchDisplayController setActive:NO animated:YES];
        [self.searchDisplayController.searchBar resignFirstResponder];
    }
}
于 2013-04-12T04:41:51.470 回答
1

尝试这个:

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

sBar.delegate = self;

sBar.showsCancelButton = YES;

[self.view addSubview:sBar];

并尝试将 release 放入 dealloc

于 2011-07-23T06:32:33.383 回答