8

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

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

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

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

有任何想法吗?

4

3 回答 3

17

Associating the search bar with a UISearchDisplayController magically provides a lot of standard look and behavior such as:

  • gray tint without affecting cancel button
  • auto showing/hiding of cancel button
  • width adjustment around any tableview indexes

In my tableview controller I've done the following:

- (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];
}
于 2010-06-30T22:59:25.300 回答
16

我完全同意Scott McCammon的观点。

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

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


- (UISearchDisplayControlelr *) searchDisplayController {
    return yourInstanceOfASearchController;
}
于 2010-10-13T18:42:46.250 回答
1

我不明白需要调用setSearchDisplayController:或覆盖searchDisplayController. 在 iOS 4.3.2 下initWithSearchBar:contentsController:似乎设置searchDisplayController为作为参数UIViewController传递的实例。contentsController也许这在早期的 iO​​S 版本中是一个问题,但在当前版本中似乎是多余的。

于 2011-05-04T15:41:57.310 回答