2
我不明白爲什麼我的scopeButtonTitles總是爲零。我遵循RayWenderlich的教程,但不同之處在於我的搜索欄中的元素數組應該從數據庫加載的範圍按鈕標題。scopeButtonTitles總是零
但我仔細檢查,我的數組裝滿了,而不是零。 scopeButtonTitles何時設置?也許這是在我的數組被初始化之前?
這裏是我的代碼:
var bottlesArray: Array<Bottle>!
override func viewDidLoad() {
super.viewDidLoad()
loadBottles() // loads elements from a DB and initialise bottlesArray
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
// Filter the array using the filter method
self.filteredBottles = self.bottlesArray.filter({(bottle: Bottle) -> Bool in
var categoryMatch = (scope == "All") || (bottle.category == scope)
// The two following line put the search string AND the matching string in Lower case and accent tolerent so, for example "Dôle" == "dole" -> true
var lowerCaseNoAccentTitle: String = NSString(data: bottle.title.lowercaseString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!, encoding: NSUTF8StringEncoding)!
var lowerCaseNoAccentSearchText: String = NSString(data: searchText.lowercaseString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!, encoding: NSUTF8StringEncoding)!
var stringMatch = lowerCaseNoAccentTitle.rangeOfString(lowerCaseNoAccentSearchText)
return categoryMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
let scopes = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
let selectedScope = scopes[self.searchDisplayController!.searchBar.selectedScopeButtonIndex] as String
self.filterContentForSearchText(searchString, scope: selectedScope)
return true
}
func searchDisplayController(controller: UISearchDisplayController!,
shouldReloadTableForSearchScope searchOption: Int) -> Bool {
let scope = self.searchDisplayController!.searchBar.scopeButtonTitles as [String]
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text, scope: scope[searchOption])
return true
}
因此,要明確,self.searchDisplayController!.searchBar
不是零,但scopeButtonTitles
是。如果我手動設置self.searchDisplayController!.searchBar.scopeButtonTitles
那麼範圍欄工作。但在教程中它會自動加載。
我不明白什麼時候scopeButtonTitles
陣列應該被填充。
這正是你應該問教程的原作者的問題。 –