使用swift3在tableview中搜索栏和部分

时间:2016-11-26 10:53:00

标签: uitableview swift3 uisearchbar

我有来自我的数据库的字母部分的tableview,我想添加搜索栏但我无法弄清楚如何过滤数据并在tableview中实现它。 我的数据库存储在两个结构中:

一个包含所有数据的结构。

第二个struct获取部分的第一个字母,第一个结构作为数组。

我的结构:

struct SentenceInfo { // First struct (holds all the data)

    let name: String
    let detail: String
    let sentence: String

    init(name: String, detail: String, sentence: String) {
        self.name = name
        self.detail = detail
        self.sentence = sentence
    }
}

struct SentenceNameSection { // Second struct (first letter and array of the first struct)

    var firstLetter: String
    var crimes: [SentenceInfo]

    init(title: String, objects: [SentenceInfo]) {
        firstLetter = title
        crimes = objects
    }
}

我的tableView:

var sections : [SentenceNameSection]!

var crimeData = [SentenceNameSection]()

var filteredData = [SentenceNameSection]()

var shouldShowSearchResults = false

var searchController: UISearchController!


func updateSearchResults(for searchController: UISearchController) {

    let searchString = searchController.searchBar.text

    filteredData = crimeData.filter({ (crime) -> Bool in
        let crimeMatch: String = crime // Error about types
    return ((crimeMatch.range(of: searchString!) != nil))
    })
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: sentenceTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifer, for: indexPath) as! sentenceTableViewCell

    let crime: SentenceInfo = sections[indexPath.section].crimes[indexPath.row]

    cell.nameLabel.text = crime.name
    cell.detailLabel.text = crime.detail
    cell.sentenceLabel.text = crime.sentence

    return cell
}

2 个答案:

答案 0 :(得分:2)

首先crimeData包含SentenceNameSection,无法与String进行比较

除了过滤包含部分的数据源数组之外,还必须使用重复循环并创建新的SentenceNameSection

此代码搜索SentenceInfo struct

中的所有三个属性
let searchString = searchController.searchBar.text!

filteredData.removeAll() // is mandatory to empty the filtered array
for section in crimeData {
    let filteredContent = section.crimes.filter { $0.name.range(of: searchString) != nil
        || $0.detail.range(of: searchString) != nil
        || $0.sentence.range(of: searchString) != nil 
    }
    if !filteredContent.isEmpty {
        filteredData.append(SentenceNameSection(title: section.firstLetter, objects: filteredContent))
    }
}

注意:当然,您必须在所有适当的表格视图数据源和委托方法中处理search案例。

答案 1 :(得分:0)

For Swift 3 , below is the sample code 

Struct BookDetails{
  var title:String?
  var author:String?
}

var filteredSearch:[BookDetails] = []

  filteredSearch = self.bookDetails.filter { (data) -> Bool in
            return data.title?.range(of: searchText, options: String.CompareOptions.caseInsensitive) != nil || data.author?.range(of: searchText, options: String.CompareOptions.caseInsensitive) != nil
        }