【发布时间】:2014-09-27 01:04:20
【问题描述】:
我在 Xcode 6 中做一个简单的项目,我想在 tableviewcontroller 中添加搜索栏,但有些东西不适合我。我是按照本教程做的 http://www.raywenderlich.com/76519/add-table-view-search-swift
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.filteredProgramy.count
} else {
return self.programy.count
}
}
这里我收到错误“致命错误:在展开可选值时意外发现 nil”。我知道为什么。完整代码在这里
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.filteredProgramy.count
} else {
return self.programy.count
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var program : Program
if tableView == self.searchDisplayController!.searchResultsTableView {
program = filteredProgramy[indexPath.row]
} else {
program = programy[indexPath.row]
}
func filterContentForSearchText(searchText: String) {
// Filter the array using the filter method
var scope = String()
self.filteredProgramy = self.programy.filter({( program: Program) -> Bool in
let categoryMatch = (scope == "All") || (program.category == scope)
let stringMatch = program.name.rangeOfString(searchText)
return categoryMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
return true
}
}
【问题讨论】:
-
该错误与搜索栏无关,与了解如何正确使用选项有关。你得到哪一行的错误?您可能正在对可选值进行强制解包并获得 nil(如错误消息所述)。
-
这里。 " if tableView == self.searchDisplayController!.searchResultsTableView {"
-
你解决了吗?
-
self.searchDisplayController为零吗? -
好的。现在我修好了。我再次浏览了您的答案,并修复了它。非常感谢男人!我没有看到“self.searchDisplayController 为零。”
标签: ios swift xcode tableview searchbar