我正在嘗試使用UISearchBar
編寫簡單的UITableView
。當我拖放一個UITableViewController
時,我沒有問題。一切正常! (見下面的代碼)iOS中未調用updateSearchResultsForSearchController 9
override func viewDidLoad() {
super.viewDidLoad()
self.searchResultsController = UISearchController(searchResultsController: nil) //initialize the search controller
self.searchResultsController.searchResultsUpdater = self //the search controller updater is this view
self.searchResultsController.dimsBackgroundDuringPresentation = false
self.searchResultsController.searchBar.sizeToFit()
self.searchResultsController.searchBar.searchBarStyle = UISearchBarStyle.Minimal
self.searchResultsController.searchBar.showsCancelButton = true
self.tableView.tableHeaderView = searchResultsController.searchBar
self.tableView.reloadData()
}
但現在,爲了實驗的目的,我用UIViewController
,並且加入了UITableView
,沒有問題顯示在表我的記錄。
然後,從故事板中添加一個UISearchBar,將其委託設置爲UIViewController,但當用戶輸入某些東西時,不調用updateSearchResultsForSearchController
方法。
這就像我的UISearchController不知道有一個UISearchBar
,並且我輸入什麼,並沒有喚起更新方法。我必須告訴UISearchController,嘿,這是你的UISearchBar
?
所以這裏是頂部的我的代碼:
class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate
{
@IBOutlet weak var mySearchBar: UISearchBar!
@IBOutlet weak var myViewTable: UITableView!
let allElements = ["H", "Li", "Na", "K", "Rb", "Cs", "Fr"]
var filteredElemetns = [String]()
var searchResultsController = UISearchController() //create a new search controller
override func viewDidLoad()
{
super.viewDidLoad()
self.searchResultsController = UISearchController(searchResultsController: nil) //initialize the search controller
self.searchResultsController.searchResultsUpdater = self //the search controller updater is this view
self.searchResultsController.dimsBackgroundDuringPresentation = false
self.searchResultsController.searchBar.sizeToFit()
self.searchResultsController.searchBar.searchBarStyle = UISearchBarStyle.Minimal
self.searchResultsController.searchBar.delegate = self
//self.myViewTable.tableHeaderView = self.searchResultsController.searchBar
}
如果我去掉最後一行,那麼我將有兩個UISearchBar
,其中之一是由故事板和補充另一個用最後一行代碼。我添加的那個,不起作用,但在myViewTable
的頂部。
你的類是否符合UISearchResultsUpdating,UISearchControllerDelegate協議? – MDB983
missing searchController.searchBar.delegate = self? –
是的,它符合。 –