【问题标题】:Adding SearchBar to NavigationBar Objective-C iOS 9将搜索栏添加到导航栏 Objective-C iOS 9
【发布时间】:2016-01-16 02:09:17
【问题描述】:

我认为标题很容易解释。我在导航控制器中嵌入了一个 tableView,并希望在导航栏中添加一个搜索栏。我认为 iOS 9 中关于搜索栏控制器的事情发生了一些变化,所以请记住,这必须适用于 iOS 9。这就是我所拥有的。毫无疑问这是错误的。

 UISearchController *searchController = [[UISearchController alloc]init];
self.searchController.searchBar.barTintColor = [UIColor whiteColor];
[self.navigationController addChildViewController:searchController];

【问题讨论】:

    标签: ios objective-c uinavigationcontroller uisearchbar


    【解决方案1】:
    //This method has deprecated in ios 8. So, before ios 8 you can use this.
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
    [searchBar sizeToFit];
    
    UISearchDisplayController *searchDisplayController= [[UISearchDisplayController alloc] initWithSearchBar:searchBar
                                        contentsController:self];
    self.searchDisplayController.searchResultsDelegate = self;
    self.searchDisplayController.searchResultsDataSource = self;
    self.searchDisplayController.delegate = self;
    self.navigationItem.titleView = searchDisplayController.searchBar;
    

    // ios8/ios9使用如下代码

    UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:self];
    // Use the current view controller to update the search results.
    searchController.searchResultsUpdater = self;
    // Install the search bar as the table header.
    self.navigationItem.titleView = searchController.searchBar;
    // It is usually good to set the presentation context.
    self.definesPresentationContext = YES;
    

    【讨论】:

    【解决方案2】:

    如果您使用的是 UISearchDisplayController,这应该可以工作。

    Apple Docs

    searchDisplayController.displaysSearchBarInNavigationBar = true
    

    【讨论】:

    • UISearchDisplayController 在 iOS 8 中已被弃用,因此对于 iOS 9 来说不是一个好的答案。
    【解决方案3】:

    通过情节提要添加它。在视图控制器场景中添加搜索栏,例如添加退出和第一响应者,然后将导航项的 titleView 提供给搜索栏。

    【讨论】:

    • 谢谢!一直在寻找这个解决方案。
    • 你是救世主兄弟:)
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 2018-03-12
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    相关资源
    最近更新 更多