Xcode13.4.1 UIKit中tableView.indexPathForSelectedRow返回nil问题求助
问题:侧滑操作触发Segue时,
tableView.indexPathForSelectedRow返回nil 通过Storyboard配置了Segue,实现leadingSwipeActions后调用tableView.indexPathForSelectedRow始终返回nil,无法获取目标行的索引信息。相关代码如下:
import UIKit class TableViewController: UITableViewController { let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return months.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = months[indexPath.row] return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "editItem" { let path = tableView.indexPathForSelectedRow print("\(path)") // 打印结果为nil } } override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let editAction = UIContextualAction(style: .normal, title: "Edit Item") { [self] (action, view, completion) in performSegue(withIdentifier: "editItem", sender: self) } editAction.backgroundColor = .systemOrange return UISwipeActionsConfiguration(actions: [editAction]) } }
原因分析
tableView.indexPathForSelectedRow仅能获取用户主动点击选中的行的索引,而侧滑操作(leadingSwipeActions)不会自动触发行的选中状态,因此调用该方法会返回nil。同时当前代码中调用performSegue时传入的sender是当前ViewController,没有携带任何行索引相关信息,导致prepare方法无法获取目标行的位置。
解决方案
方案一:直接传递indexPath作为sender(推荐)
在侧滑操作的闭包中,将当前行的indexPath作为sender传给performSegue,再在prepare方法中从sender取出索引:
- 修改侧滑操作的代码:
let editAction = UIContextualAction(style: .normal, title: "Edit Item") { [self] (action, view, completion) in performSegue(withIdentifier: "editItem", sender: indexPath) }
- 修改
prepare方法:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "editItem" { if let indexPath = sender as? IndexPath { print(indexPath) // 可正确获取侧滑行的索引 // 后续可将对应数据传递给目标ViewController,示例: // let targetVC = segue.destination as! ViewController // targetVC.selectedMonth = months[indexPath.row] } } }
方案二:手动选中行再触发Segue(不推荐)
若一定要使用indexPathForSelectedRow,可在触发Segue前手动选中该行,但会导致行出现高亮选中状态,影响用户体验:
let editAction = UIContextualAction(style: .normal, title: "Edit Item") { [self] (action, view, completion) in tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) performSegue(withIdentifier: "editItem", sender: self) // 可选:跳转后取消选中,避免残留高亮 // tableView.deselectRow(at: indexPath, animated: false) }
内容的提问来源于stack exchange,提问作者maxMas
相关产品推荐
相关产品推荐

