2016-01-27 93 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) 
} 

正確的修復方法當然是自定義控件,但我們沒有時間在此階段編寫自定義的東西。

相關問題