如何在UITablView中自定义搜索功能

时间:2015-07-30 09:33:20

标签: swift uitableview uisearchbar searchbar xcode6.3

在搜索栏结果中我想首先使用AnchoredSearch选项进行比较,如果我没有得到这个值,那么我想仅使用CaseInsensitiveSearch选项进行比较。

我已将下面的代码附加到searchBar。

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

        self.array = self.getUniqArrayData(self.array)
        filteredTableData = array.filter({ (text) -> Bool in
            let tmp: NSString = text
            var range = tmp.rangeOfString(searchText, options: (NSStringCompareOptions.AnchoredSearch | NSStringCompareOptions.CaseInsensitiveSearch ))

            return range.location != NSNotFound
        })

        if(searchText == ""){

            searchActive = false;
        } else {
            searchActive = true;
        }
        self.xyztable.reloadData()
    }

请让我知道如何首先使用AnchoredSearch进行过滤,如果我在其中找不到任何内容,则使用CaseInsensitiveSearch选项进行搜索。

任何示例或示例代码或链接都会有所帮助

1 个答案:

答案 0 :(得分:4)

这是简单的排序。我清理了一些东西; tmp是不必要的。

// I don't think you intend to overwrite the underlying data just because
// the user did a search. Did you mean to do a local variable:
let uniqArray = self.getUniqArrayData(self.array)
let tryAnchored = uniqArray.filter { (text) -> Bool in
    var range = text.rangeOfString(searchText, options: .AnchoredSearch)
    return range.location != NSNotFound
}
if tryAnchored.count > 0 {
    self.filteredTableData = tryAnchored
}
else {
    // maybe have a local 'let' here too, and if this one also comes up
    // empty, don't reload the table data at all?
    self.filteredTableData = uniqArray.filter { (text) -> Bool in
        var range = text.rangeOfString(searchText, options: .CaseInsensitiveSearch)
        return range.location != NSNotFound
    }
}