scopeButtonTitles总是为零

时间:2015-01-12 16:32:17

标签: ios swift uisearchbar uisearchdisplaycontroller

我不明白为什么我的scopeButtonTitles总是为零。我按照RayWenderlich的教程进行了操作,但区别在于我的搜索栏应该从数据库中加载我的搜索栏中的元素数组。

但是我仔细检查过,我的阵列装得很好,而不是零。 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数组。

0 个答案:

没有答案