2016-01-27 60 views
0

在我的应用程序中,我需要创建一个搜索建议界面 - 与Google搜索非常相似(它在搜索字段中键入时开始显示建议)。有没有办法与UISearchController创建“搜索建议”界面

我在导航栏的搜索栏中UISearchController做到了,设置它是这样的:

// setup search controller 
searchController = UISearchController(searchResultsController: searchSuggestionsController) 
self.searchController.searchResultsUpdater = searchSuggestionsController 
self.searchController.hidesNavigationBarDuringPresentation = false 
self.navigationItem.titleView = self.searchController.searchBar 

// ISSUE!! definesPresentationContext needs to be false or I can't push this 
// controller multiple times on the navigation stack 
self.definesPresentationContext = true 

而当搜索控制器推到导航堆栈中第一次工作得很好,它不“T让搜索栏获取焦点当推第二次,如下图所示

with definesPresentationContext = true, it doesn't let search bar get focus the second time I push search controller on to the navigation stack

,但如果我将它设置为false:当我开始输入到搜索栏,导航酒吧(连同搜索栏)消失。这是意料之中的,因为(因为definesPresentationContext = falseUISearchController行为现在正试图以显示其对UINavigationController的视图的俯视图,如下图所示:

with definesPresentationContext = false, navigation bar disappears as soon as I start typing

有没有办法通过UISearchController实现这一目标?如果没有,我应该如何为此创建一个自定义控件的指针? (动画中显示的最小应用的代码可以是downloaded here

回答

1

不可能像这样使用UISearchController。已知UISearchBar和UINavigationBar不能很好地一起玩。我决定要做的是,每次用户点击搜索按钮,我检查childViewControllers我的导航控制器阵列,如果我在那里找到SearchViewController的实例,我会回到它。否则我推它。

// This function lives inside a UINavigationController subclass and is called whenever I need to display the search controller 
func search() { 
    if let _ = self.topViewController as? SearchViewController { 
     return 
    } 

    var existingSearchController: SearchViewController? = nil 
    for childController in self.childViewControllers { 
     if let searchController = childController as? SearchViewController { 
      existingSearchController = searchController 
     } 
    } 

    if let searchController = existingSearchController { 
     self.popToViewController(searchController, animated: true) 
     return 
    } 

    self.performSegueWithIdentifier(StoryboardConstants.SegueShowSearchController, sender: nil) 
} 

正确的修复方法当然是自定义控件,但我们没有时间在此阶段编写自定义的东西。

相关问题