【问题标题】:Passing an array of structs from UICollectionView to DetailView and use the indexes to go from one item to another?将一组结构从 UICollectionView 传递到 DetailView 并使用索引从一个项目转到另一个项目?
【发布时间】:2017-05-01 16:41:53
【问题描述】:

我有一个由 productItem 结构数组填充的 UICollectionView,结构蓝图在它自己的名为 ProductoItem.swift 的 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 以仅使用产品单元格的数据填充它,然后我还想要两个按钮到下一个/上一个产品,它只是转到我的结构的下一个/上一个索引值。我该怎么做?

【问题讨论】:

  • 你是否使用“didSelectItemAtIndexPath”来打开你的detailView?
  • 在准备中,您可以获取按下 yourCollectionView.indexPathForCell(cell) 的单元格的索引,然后从具有索引的数组中获取数据。看看这个问题。stackoverflow.com/questions/31914213/…
  • @RemyCilia 是的,我这样做了,如果我不使用结构,我使用字典数组,我可以通过这样做获得当前的索引路径。让 currentProduct = arrayOfDictionaries[indexPath.item] 但是当我使用结构尝试相同时,我得到一个空数组。无论如何,当我使用字典数组时,我可以获得一个产品的对象执行该方法,但我需要的是带来整个结构,使用所选单元格的索引中的值来填充 detailView,在这个视图中我有两个按钮可以转到下一个/上一个产品,因此当您单击它们时,索引会发生变化)
  • @Yan 我可以通过在 prepare(for segue:) 方法中执行此操作来获取按下的单元格的索引:let item = self.collectionView.indexPathsForSelectedItems 但我需要的是使用它indexPath 和我的结构数组,所以当我进入详细视图时,选择用来填充数据的结构是选择的。在那里,我需要能够转到下一个或上一个索引值,以便切换到下一个/上一个产品。

标签: swift struct uicollectionview uicollectionviewcell detailview


【解决方案1】:

首先,在您的 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'。

【讨论】:

  • 它工作得很好,我之前没有感谢你,因为我在度假,但你的解决方案很棒,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多