我正在尝试重新创建此UISearchBar(如表搜索示例代码中所示):
alt text http://img168.imageshack.us/img168/6378/43558113.png
我见过的所有这些例子都涉及使用xib,但我需要以编程方式进行。问题是改变色调颜色也会改变取消按钮的色调:
alt text http://img243.imageshack.us/img243/1375/screenshot20100527at944.png
有什么想法吗?
答案 0 :(得分:17)
将搜索栏与UISearchDisplayController相关联会神奇地提供许多标准外观和行为,例如:
在我的tableview控制器中,我完成了以下操作:
- (void)viewDidLoad {
[super viewDidLoad];
// setup searchBar and searchDisplayController
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[searchBar sizeToFit];
searchBar.delegate = self;
searchBar.placeholder = @"Search";
self.tableView.tableHeaderView = searchBar;
UISearchDisplayController *searchDC = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
// The above assigns self.searchDisplayController, but without retaining.
// Force the read-only property to be set and retained.
[self performSelector:@selector(setSearchDisplayController:) withObject:searchDC];
searchDC.delegate = self;
searchDC.searchResultsDataSource = self;
searchDC.searchResultsDelegate = self;
[searchBar release];
[searchDC release];
}
答案 1 :(得分:16)
我完全同意 Scott McCammon 。
但在performSelector:withObject:
上使用setSearchDisplayController:
不是我的方法。这取决于私有API,它可以随时改变。如果Apple将删除他们的私有实现,您的应用程序将崩溃。
更好的方法是覆盖视图控制器中的searchDisplayController:
以返回UISearchDisplayController
的实例:
- (UISearchDisplayControlelr *) searchDisplayController {
return yourInstanceOfASearchController;
}
答案 2 :(得分:1)
我不理解调用setSearchDisplayController:
或覆盖searchDisplayController
的必要性。在iOS 4.3.2下initWithSearchBar:contentsController:
似乎为searchDisplayController
实例设置UIViewController
实例作为contentsController
参数。也许这是早期iOS版本中的问题,但在当前版本中似乎是多余的。