首页 > 解决方案 > 在uitableview中过滤后执行segue

问题描述

我目前正在创建一个在 uitableview 上有位置列表的应用程序。还有一个过滤功能,可以根据类别过滤位置。当不过滤时,uitableviewcell 会在单击时执行 segue,并且正确的数据会加载到目标视图控制器中。但是,当我过滤 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)!]

    }
}
}

标签: iosswiftuitableviewfiltersegue

解决方案


发生这种情况是因为即使在过滤时您也在使用shoutoutArray 。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
    }
}

推荐阅读