如何通过searchController加载来自不同数组的两个值?

时间:2016-07-20 10:55:47

标签: swift uisearchcontroller

我必须使用填充searchController值的数组。

let textLabel = ["Uni", "Uni", "Faber-Castell", "Faber-Castell","Faber-Castell", "Pilot", "Pilot"]
let detailTextLabel = ["Pen", "Pencil", "Crayon", "Mechanical Pencil", "Contour Pencil", "Eraser", "Sharpener"]

这两个数组在重新加载UITableViewController. Like(Uni,Pen),(Uni,Pencil),(Faber-Castell,Crayon)......的数据时配对...

成对出现,第一个是单元格标题,第二个是副标题。我跟着iOSCreator's tutorial

我的问题是,当我搜索文本时,它只更新标题部分,而不是预期的副标题。

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    // 3
    if (self.resultSearchController.active) {
    // it only updates textLabel. But when I add detailTextLabel 
    // subtitles comes wrong because first array contains one element
    // more than twice.
      cell.textLabel?.text = filteredTableData[indexPath.row]

      return cell
    } else {
      cell.textLabel?.text = tableData[indexPath.row]

      return cell
    }
  }

  func updateSearchResultsForSearchController(searchController: UISearchController) {
    filteredTableData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
    let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
    filteredTableData = array as! [String]

    self.tableView.reloadData()
  }

1 个答案:

答案 0 :(得分:-1)

像这样使用单个数组:

let penList = ["Uni:Pen", "Uni:Pencil", "Faber-Castell:Crayon"]

let result = filteredTableData[indexPath.row] // example: "Uni:Pen"
let clearResult = String(result.characters.map { $0 == ":" ? " " : $0 })
// clearResult like this "Uni Pen"
cell.textLabel?.text = clearResult

您也可以分开数据

let result = filteredTableData[indexPath.row]
let resultArray = result.componentsSeparatedByString(":")
let firstText = resultArray[0] // title text
let secondText = resultArray[1] // subtitle text