You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将UICollectionView中的Foods数据传递至详情ViewController?

从JSON获取数据后,将UICollectionView数据传递到详情页

需求

实现从JSON加载数据到UICollectionView后,点击单元格将对应Foods模型数据传递至DetailScreen详情页面。

已定义的Foods模型类

class Foods: Codable {
    var id : Int?
    var name : String?
    var image : String?
    var price : Int?
    var category : String?
    
    init(id: Int?, name: String?, image: String?, price: Int?, category: String?) {
       self.id = id
       self.name = name
       self.image = image
       self.price = price
       self.category = category
   }  
}

HomeScreen视图控制器代码

class HomeScreen: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITextFieldDelegate, UICollectionViewDelegateFlowLayout { 
 
    var foodsList = [Foods]()
    
    @IBOutlet weak var collectionView: UICollectionView!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toDetail" {
            if let food = sender as? Foods {
                let detailScreen = segue.destination as! DetailScreen
                detailScreen.food = food
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return foodsList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProductsCollectionViewCell", for: indexPath) as? ProductsCollectionViewCell else {
            return UICollectionViewCell()
        }
        cell.configure(item: foodsList[indexPath.row])
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let food = foodsList[indexPath.row]
        performSegue(withIdentifier: "toDetail", sender: food)
        collectionView.deselectItem(at: indexPath, animated: true)
    }
}

关键补充说明

  • 确保Storyboard中已配置HomeScreen到DetailScreen的segue,且segue的identifier设置为toDetail
  • DetailScreen中必须声明接收数据的属性:
    var food: Foods?
    
  • JSON数据解析到foodsList的示例逻辑(确保数据正确加载到集合视图):
    // 假设你已获取到JSON数据
    if let jsonData = yourJSONData {
        do {
            foodsList = try JSONDecoder().decode([Foods].self, from: jsonData)
            collectionView.reloadData()
        } catch {
            print("JSON解析失败:\(error.localizedDescription)")
        }
    }
    

内容的提问来源于stack exchange,提问作者Frank Castle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:21:32