我一直在阅读各种执行segue的方法。我想通过点击单元格来进行推送。我在情节提要中有主题,所以我没有使用didSelectForRow函数:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let selectedRow = self.tableView.indexPathForSelectedRow as? Int else { return }
if segue.identifier == "detail", let vc = segue.destination as? DetailViewController {
vc.playerImage = UIImageView(image: UIImage(named: "userIcon"))
vc.currentRankingLabel.text = String(players[selectedRow].ranking)
vc.scoreLabel.text = String("\(players[selectedRow].wins) - \(players[selectedRow].losses)")
}
}
这是我目前所掌握的。它可以编译,但是单元格不会对点击做出反应!
答案 0 :(得分:0)
indexPathForSelectedRow
从未是Int
,而是IndexPath?
。删除条件下调,并从其row
属性中获取行
guard let selectedPath = self.tableView.indexPathForSelectedRow else { return }
let selectedRow = selectedPath.row
if segue.identifier == "detail", let vc = segue.destination as? DetailViewController {
vc.playerImage = UIImageView(image: UIImage(named: "userIcon"))
vc.currentRankingLabel.text = String(players[selectedRow].ranking)
vc.scoreLabel.text = String("\(players[selectedRow].wins) - \(players[selectedRow].losses)")
}
但是如果segue连接到了单元格,我建议使用代表单元格的sender
参数
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detail", let vc = segue.destination as? DetailViewController {
let selectedPath = self.tableView.indexPath(for: sender as! UITableViewCell)!
let selectedRow = selectedPath.row
vc.playerImage = UIImageView(image: UIImage(named: "userIcon"))
vc.currentRankingLabel.text = String(players[selectedRow].ranking)
vc.scoreLabel.text = String("\(players[selectedRow].wins) - \(players[selectedRow].losses)")
}
}
重要提示:
请注意,prepare(for
中未连接目标控制器中的插座,因此将不显示任何内容,甚至导致代码崩溃。
答案 1 :(得分:0)
我认为您需要在选择单元格时致电performSegue
,如下所示
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "detail", sender: indexPath)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let selectedPath = sender as? IndexPath, let selectedRow = selectedPath.row, let player = players[selectedRow] else {
return
}
if segue.identifier == "detail", let vc = segue.destination as? DetailViewController {
vc.playerImage = UIImageView(image: UIImage(named: "userIcon"))
vc.currentRankingLabel.text = String(player.ranking)
vc.scoreLabel.text = String("\(player.wins) - \(player.losses)")
}
}