在uitableview中过滤后执行segue

时间:2019-06-12 01:25:29

标签: ios swift uitableview filter segue

我当前正在创建一个在uitableview上具有位置列表的应用。还有一个过滤功能,可以根据类别对位置进行过滤。如果不进行过滤,则uitableviewcell在单击时会执行segue,并且正确的数据会加载到目标viewcontroller中。但是,当我过滤tableview时,单元格会填充正确的数据,但是当我单击该单元格时,目标viewcontroller总是从UNFILTERED tableview中的第一个单元格加载数据。

我正在使用的代码:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "shoutoutCell", for: indexPath) as! shoutoutTableViewCell

    var shout = shoutout[indexPath.row]

    if isFiltering == true {
        shout = filteredShoutout[indexPath.row]
      } else {
        shout = shoutout[indexPath.row]
    }

    cell.shoutout = shout
     cell.showsReorderControl = true
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)  {
     var object = shoutout[indexPath.row]

    if isFiltering == true {
        object = filteredShoutout[indexPath.row]
    } else {
        object = shoutout[indexPath.row]
    }
   performSegue(withIdentifier: "shoutoutDetailSegue", sender: object)


}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoutoutDetailSegue" {
    if let destination = segue.destination as? shoutoutDetailViewController {
      //  destination.shoutoutSelected = sender as! object
        destination.shoutoutSelected = shoutout[(tableView.indexPathForSelectedRow?.row)!]

    }
}
}

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为即使在过滤时,您也在shoutout中使用prepare(for segue数组。

destination.shoutoutSelected = shoutout[(tableView.indexPathForSelectedRow?.row)!]

将其更改为

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoutoutDetailSegue" {
    if let destination = segue.destination as? shoutoutDetailViewController {
        // Here `Model` should be your class or struct
        destination.shoutoutSelected = sender as! Model
    }
}

或者将您的逻辑从didSelectRowAt

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "shoutoutDetailSegue" {
    if let destination = segue.destination as? shoutoutDetailViewController {
        if isFiltering == true {
            object = filteredShoutout[indexPath.row]
        } else {
            object = shoutout[indexPath.row]
        }
        destination.shoutoutSelected = object
    }
}