首页 > 解决方案 > 将数组数据从 CollectionView 传递到下一个 ViewController

问题描述

我正在开发 IOS 应用程序,我想将食物图像和标题传递给下一个 ViewController。食物图像和标题从 API 中检索并存储在数组中,并使用 SDWebImage 显示食物图像和标题。食物图像和标题使用 public var foodTitle = String 和 public var foodImage = String。

是否可以将单击的图像数据从集合视图单元传递到下一个 ViewController?

我尝试使用下面的代码,但仍然无法在 ViewController 上显示图像和标题。

   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

    let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let placeOrder = mainStoryboard.instantiateViewController(withIdentifier: "PlaceOrderViewController") as! PlaceOrderViewController
    placeOrder.name = self.foodTitle[indexPath.item]
    placeOrder.image = self.foodImage[indexPath.row]
    self.navigationController?.pushViewController(placeOrder, animated: true)
}

下面是集合视图的代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MainPageCollectionViewCell
cell.FoodTitle.text = self.foodTitle[indexPath.item]
cell.Food.sd_setImage(with: URL(string: foodImage[indexPath.row]),placeholderImage: UIImage(named: "image"))
    return cell
}

标签: viewcontrollercollectionviewswift4.2

解决方案


当您传递图像 URL 和标题时,这是可能的。在下一个 viewController 中创建一个图像视图,并通过 SDWebImage 异步调用加载图像视图的图像。


推荐阅读