灰色UISearchBar以编程方式匹配范围栏

chr*_*o16 9 iphone uisearchbar tintcolor

我正在尝试重新创建这个UISearchBar(如表搜索示例代码中所示):

替代文字http://img168.imageshack.us/img168/6378/43558113.png

我见过的所有这些例子都涉及使用xib,但我需要以编程方式进行.问题是改变色调颜色也会改变取消按钮的色调:

替代文字http://img243.imageshack.us/img243/1375/screenshot20100527at944.png

有任何想法吗?

Sco*_*mon 17

将搜索栏与UISearchDisplayController相关联会神奇地提供许多标准外观和行为,例如:

  • 灰色色调不影响取消按钮
  • 自动显示/隐藏取消按钮
  • 任何tableview索引周围的宽度调整

在我的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];
}
Run Code Online (Sandbox Code Playgroud)

  • 如果有人想要使用它 - 我的应用程序因使用非公共API而被拒绝.setSearchDisplayController是罪魁祸首. (2认同)

Jor*_*ers 16

我完全赞同Scott McCammon.

但是使用performSelector:withObject:on setSearchDisplayController:不会是我的方法.这取决于私有API,它可以随时改变.如果Apple将删除他们的私有实现,您的应用程序将崩溃.

更好的方法是覆盖searchDisplayController:视图控制器中的以返回以下实例UISearchDisplayController:


- (UISearchDisplayControlelr *) searchDisplayController {
    return yourInstanceOfASearchController;
}
Run Code Online (Sandbox Code Playgroud)