2017-02-18 68 views
1

一個UISearchBar或者是手動執行的搜索欄上的所有需要​​的觀點的正確方法簡單的方法? 我必須在我的應用程序的幾乎每個視圖中添加一個搜索欄(除了在每個視圖導航欄上添加按鈕)。但我不確定實現這一目標的最佳方法是什麼。
如何添加在每個視圖

  1. 我應該繼承一個導航欄或整個導航控制器嗎?
  2. 或者是以正確方式在所有需要的視圖上手動實施搜索欄的簡單方法?

如果我應該繼承哪個類是正確的? 我的想法是子類UINavigationController,添加UISearchBar後搜索結果中取出,打開與搜索結果的UITableViewController

這是我目前的做法(不執行搜索欄委託只是爲了檢查,如果我是一個有效的解決方案)

import UIKit 

class MyNavigationControllerViewController: UINavigationController { 

    var searchController : UISearchController! 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     self.navigationBar.backgroundColor = UIColor.red 
     self.createSearchBar() 
    } 

    func createSearchBar() { 
     let searchBar = UISearchBar() 
     searchBar.showsCancelButton = true 
     searchBar.placeholder = "Search" 
     // searchBar.delegate = self 
     self.navigationItem.titleView = searchBar 
    } 
} 

至少,調試器進入MyNavigationController但無論是搜索欄是可見的,也不是紅色導航欄。

+0

對不起,但由於剪貼板複製我的mac上的錯誤,同時編輯你的問題,我複製了句子。我指望編輯請求被拒絕,因此SO沒有_edit cancel_功能。你能否正確地重構問題? – ystack

回答

1

我建議使用一協議與一個擴展將提供導航欄和項目的配置。然後,您可以擴展任何視圖控制器以符合它並使用該協議的默認實現。

import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     configureNavigationBar() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
} 

extension ViewController: SearchController { } 

protocol SearchController: class { } 
extension SearchController where Self: UIViewController { 

    func configureNavigationBar() { 
     navigationController?.navigationBar.backgroundColor = UIColor.red 
     let search = UISearchBar() 
     search.placeholder = "Search" 
     search.showsCancelButton = true 
     navigationItem.titleView = search 
    } 
} 
相關問題