过滤器UISearchController - Swift之后的didSelectRowAtIndexPath索引路径

Hel*_*ood 3 uitableview ios swift

我正在一个分段表中实现一个带有UISearchController的搜索栏.到现在为止还挺好.

主要问题是,当过滤后的结果出现时,它是一个没有部分和更少行的全新表.

当选择行时,我对数组中的那个位置执行segue,但是详细视图期望来自主数组的精确行或索引,这是我无法从过滤的对象数组中获得的,这可能是[0 ] [1] [2]在300个元素中.

我想我可以将所选对象与主数组进行比较并假设没有重复项,从那里获取索引并将其传递给...但这对我来说似乎效率很低.

Apple在联系人应用程序中过滤联系人时做了类似的事情(我很遗憾不知道如何).他们如何通过联系对象?这几乎是我的目标.

在这里,我告诉你我正在做的事情的片段:

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if(self.resultSearchController.active) {
            customerAtIndex = indexPath.row // Issue here
            performSegueWithIdentifier("showCustomer", sender: nil)
        }
        else {
            customerAtIndex = returnPositionForThisIndexPath(indexPath, insideThisTable: tableView)
            performSegueWithIdentifier("showCustomer", sender: nil)
        }
    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showCustomer" {
            if let destination = segue.destinationViewController as? CustomerDetailViewController {
                destination.newCustomer = false
                destination.customer = self.customerList[customerAtIndex!]
                destination.customerAtIndex = self.customerAtIndex!
                destination.customerList = self.customerList
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

sah*_*108 6

你可以用另一种方式做,这是一个技巧,但它的工作原理.首先改变你的didSelectRowAtIndexPath如下:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var object :AnyObject?
        if(self.resultSearchController.active) {
            object = filteredArray[indexPath.row]
        }
        else {
            object = self.customerList[indexPath.row]
        }

        performSegueWithIdentifier("showCustomer", sender: object)
    }
Run Code Online (Sandbox Code Playgroud)

现在,在prepareForSegue,返回对象并将其发送到您的详细视图控制器

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showCustomer" {
        if let destination = segue.destinationViewController as? CustomerDetailViewController {
            destination.newCustomer = false
            destination.customer = sender as! CustomerObject
            destination.customerAtIndex = self.customerList.indexOfObject(destination.customer)
            destination.customerList = self.customerList
        }
    }
}
Run Code Online (Sandbox Code Playgroud)