将结构数组从 UICollectionView 传递到 DetailView 并使用索引从一项转到另一项?

Passing an array of structs from UICollectionView to DetailView and use the indexes to go from one item to another?

我有一个由一组 productItem 结构填充的 UICollectionView,结构蓝图在它自己的 swift 文件中,名为 ProductoItem.swift

struct ProductoItem {
    let id: Int
    let name: String
    var price: String
    var picture: String
    var description: String
}

这行得通,我可以用它成功填充我的 UICollectionView,我现在要做的是将这个结构传递给 detailView,所以我在 detailView 中创建了这个变量。

var productos = [ProductoItem]()

然后我将以下代码放入我的 prepareForSegue 方法中。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "detalleProducto" {

        let controller = segue.destination as! ProductoDetailViewController

        controller.productos = productos
    }
}

我不知道怎么做知道的是:

首先,当我们发送整个结构数组时,我想将存储在 CollectionView 单元格索引中的值传递给 DetailView 以仅使用产品单元格的数据填充它,然后我还想要两个按钮转到下一个/上一个产品,只是转到我的结构的下一个/上一个索引值。我该怎么做?

首先,在您的 detailView 中创建一个新的 'currentIndex: Int' 属性。

从您的第一个 UIViewController(具有 UICollectionView 的那个),将当前索引和数组传递给您的 DetailView:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "detalleProducto" {
        let controller = segue.destination as! ProductoDetailViewController
        controller.productos = productos

        // do whatever you need to get your index
        controller.currentIndex = self.collectionView.indexPathsForSelectedItems()[0].row
    }
}

然后在您的 DetailView 中,您有数组和当前索引,因此您可以通过以下方式获取该特定产品的信息:

let currentProduct = self.productos[currentIndex]

要转到上一个或下一个,您可以递增或递减 'currentIndex'。