Swift 如何从 CollectionviewCell 中提取 indexPath 值?

Swift How to segue indexPath value from CollectionviewCell?

我希望能够在我的 DetailViewController. 中重新加载该值 如何 segue 选定的 indexPath 以便我可以在下一个视图控制器中调用该值?

在我的 didSelectItemAt 我有:

let monsters: Monsters!

let mons: [Monsters] = Data().mons
monsters = mons[indexPath.row] 

self.performSegue(withIdentifier: "DetailVC", sender: monsters)

您可以在 DetailViewController 中创建一个 monster 属性,然后在调用 prepare(for segue:)

时分配它
// This would be a property at the top of DetailViewController
var monster:Monster?

然后在执行segue的VC里面,为selectedMonster创建一个属性,根据indexPath:

赋值
var selectedMonster:Monster?

然后当您的用户选择一个单元格时:

selectedMonster = mons[indexPath.row] 

在同一个 VC 中,调用 performSegue(withIdentifier:) 时将调用此方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "DetailVC" {
        let detailVC = segue.destination as! DetailViewController
        detailVC.monster = selectedMonster
    }
}

您可能需要检查您如何调用 performSegue(withIdentifier:),通常您希望发件人是 self,即:

performSegue(withIdentifier: "DetailVC", sender: self)