Ios 向tableviewcell传递正确图像时出现问题

Ios 向tableviewcell传递正确图像时出现问题,ios,swift,uiviewcontroller,uicollectionview,swift-structs,Ios,Swift,Uiviewcontroller,Uicollectionview,Swift Structs,这是我的结构 struct ProductImage { let id : String let url : URL let isDefault : Bool } struct Product { let name : String let id : String var images = [ProductImage]() init(name : String, id: String) { self.name = name

这是我的结构

struct ProductImage {
   let id : String
   let url : URL
   let isDefault : Bool
}

struct Product {
    let name : String
    let id : String
    var images = [ProductImage]()

    init(name : String, id: String) {
        self.name = name
        self.id = id
    }

    mutating func add(image: ProductImage) {
        images.append(image)
    }
}
现在我在collectionview上加载了一个图像,单击一个按钮,我想将该图像传递到tableviewcell。collectionview确实有两个标签,它们的名称和id都已成功传递……但我无法弄清楚如何传递图像。以下是迄今为止点击“销售”按钮时发生的情况

func SellBtnTapped(_ sender: UIButton) {

   let indexPath = collectionView?.indexPath(for: ((sender.superview?.superview) as! RecipeCollectionViewCell))

   let myVC = storyboard?.instantiateViewController(withIdentifier: "productSellIdentifier") as! sellTableViewController
   let productObject = productData1[(indexPath?.row)!]

   if selectedItems == nil {
       //selectedItems is an array which will hold all struct items.
       selectedItems = [Product(name:productObject.name, id: productObject.id)]
   } else {
       selectedItems?.append(productObject)
   }

   myVC.arrProduct = selectedItems
   navigationController?.pushViewController(myVC, animated: true)
}
这就是我在tableviewcell中分配图像和其他数据的方式。这是加载单元格的tableview的cellForRow..的代码

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
             let cell: sellTableViewCell = tableView.dequeueReusableCell(withIdentifier: "sellProductIdentifier") as! sellTableViewCell

    //cell.prdImgView?.image =.... by doing this, the images are displayed in the tableviewcell in the same order as they are displayed in the collectionview cells irresoective of which cell was clicked. i.e clicking on btn on 1st collection view item shows the image on that collection view item on the tableviewcell.And when I click on the btn on the 4th collectionview item the image shown on the tableview cell will be that of the 2nd collectionview item...     
             cell.prdImgView?.image = self.appDelegate.commonArrayForURLImages[indexPath.row]                              

             let product = arrProduct?[indexPath.row]
             cell.produvtNameLabel.text = product?.name
             cell.rateTextField.text = product?.theRate

             return cell
        }
这就是传递到tableview单元格的数组获取图像的方式

var theProduct = Product(name: name, id: id, theRate: rate, quantity: qty, sku: skuCode, prdCateg: prodCat, prodDescr: description)
if let images1 = anItem["product_images"] as? [[String:String]] {
    for image in images1 {
        guard let imageId = image["id"],
            let url1 = image["image"],
            let isDefault = image["is_default"] else { continue }
        let productImage = ProductImage(id: imageId, url: URL(string: url1)!, isDefault: isDefault == "1")
        theProduct.add(image: productImage)
        self.productData1.append(theProduct)
        self.imgData.append(productImage)
        let url = URL(string: url1)
        if let data = try? Data(contentsOf: url!) {
            let img = UIImage(data: data)
            print(img!)
            self.arrayOfURLImages.append(img!)
        }

        self.appDelegate.commonArrayForURLImages = self.arrayOfURLImages
    }
}

结构为您提供了成员式初始化器,因此在大多数情况下您不需要自己的初始化器。在您的代码中,您的产品初始化器只保存名称和id,而不是productImage的数组,您似乎有一个单独的函数来保存该数据,我认为这里不需要它。因此,我所做的只是为它创建了一个数组类型[ProductImages]并与默认初始值设定项绑定

import Foundation

struct ProductImage {
    let id        : String?
    let url       : String? // Keep this string
    let isDefault : Bool?
}

struct Product {
    let name   : String?
    let id.    : String?
    var images : [ProductImage]?
}
ControllerClasswith collection视图获取初始数据-:

在控制器类中,我创建了2个数组-:

1,用于保存图像的数据

2保存整个产品信息的数据

为了保存数据,我现在只传递常量值。在viewDidLoad中,我为每个对象调用了initialiser-:

1保存图像对象数据

2.产品对象数据

3将这两个对象附加到适当的数组中

import UIKit
class MyViewController: UIViewController {

    @IBOutlet weak var mainCollectionView: UICollectionView!

    // ARRAY OBJECT OF TYPE PRODUCT AND PRODUCT IMAGE

    var imageData   = [ProductImage]()
    var productData = [Product]()


    //viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        modelDataForCollectionView()
        }

    func modelDataForCollectionView(){

        // GET IMAGE DATA

        let imageObject = ProductImage(id: "1", url: "your url", isDefault: true)
        imageData.append(imageObject)

        // MODEL FOR PRODUCTS

        let productObject = Product(name: "", id: "", images: imageData)
        productData.append(productObject)
    }

    //didReceiveMemoryWarning
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

// MyViewController extending collection view

extension MyViewController :UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    //numberOfItemsInSection
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return productData.count
    }


    //dequeueReusableCell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionCell
        cell.sendButton.addTarget(self, action: #selector(sendDataToTable), for: UIControlEvents.touchUpInside)
        return cell
    }

    //numberOfSections

    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }

    // sizeForItemAt for each row
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return CGSize(width: view.frame.width, height: 200)
    }

    func sendDataToTable(sender:UIButton){
        let index = mainCollectionView.indexPath(for: sender.superview?.superview as! CollectionCell)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let Controller = storyboard.instantiateViewController(withIdentifier: "tableData") as! ViewController1
        Controller.dataForTableView = productData[(index?.row)!].images
        self.navigationController?.pushViewController(Controller, animated: true)
    }

}
现在,当您点击UICollectionViewCell中的按钮时,获取点击的索引,并从product array中读取该索引处存在的product对象。之后,您可以轻松地将所需数据传递给表viewSecond class

第二类控制器-:

一旦你们在第二个类中获得了图像URL和任何其他必需的信息,你们就可以很容易地在表中显示这些信息。为了获得图像,你们可以向服务器调用api。我希望这对你们有所帮助

解析代码-:


@bws是的,当然。@Tushar Sharma尝试过你的方法。但似乎不起作用。你的方法似乎与我的不同…我尝试过将你的建议应用到我已有的内容中,但没有起作用。你能建议其他方法将正确的图像传递到tableviewcell吗?@bws你面临的问题是什么?你能解释一下吗用你尝试过的东西来标注你的代码日期?问题是…selectedItems数组拥有所有的结构元素。因此,即使是图像也必须添加到这个数组中。一旦我们能够做到这一点,我认为这个问题可以得到解决。但是如何做到这一点,我无法弄清楚。当你的收集类别ss正在加载数据并将数据保存在product array中解析json数据(如果有的话),因为product array还保存类型为image struct的数组,在点击采集单元时,只需从product array读取点击的单元索引,并在该索引处获取适当的产品对象,该索引也将具有该索引的图像url,一旦获得该索引,就可以通过要求红色数据到第二个控制器。您不能直接传递图像,您需要将名称或url保存为字符串。
 import UIKit

    class ViewController1: UIViewController {

// ARRAY TO HOLD IMAGE DATA FOR TAPPED COLLECTION CELL

        var dataForTableView:[ProductImage]?
        var name            : String?
        var id              : String?

        @IBOutlet weak var secondTable: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.

            // CHECK FOR DATA

            print(dataForTableView?[0].url as Any) // Optional("your url")
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

    }

    extension ViewController1 : UITableViewDelegate,UITableViewDataSource{
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
            return 1
        }


        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell1") as! testingCell2
            return cell
        }

        // Number of sections in table

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }// Default is 1 if not implemented

        public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
            return 50
        }

    }
var imageUrl:String?
var imageId:String?
var isDefaults:String?
var productId:String?
var productIdTitle:String?
var productIdImageWithPath:String?

//MARK : Call Back Delegate Methods

    func apiSuccessResponse(_ response: Dictionary<String, AnyObject>) {

        print(response)
        if let actualStyleData = response["Productdata"]  as? [Dictionary<String, AnyObject>]{

            for object in actualStyleData{

                if let id = object["product_id"] as? String{
                    productId = id
                }else{
                    productId = ""
                }
                if let title = object["product_name"] as? String{
                    productIdTitle = title
                }

                if let imageDetails = object["product_images"] as? [Dictionary<String, AnyObject>]{
                    for details in imageDetails{
                        if let id = details["id"] as? String{
                            imageId = id
                        }
                        if let url = details["image"] as? String{
                            imageUrl = url
                        }
                        if let isDefault = details["is_default"] as? String{
                           isDefaults = isDefault
                        }
                        let saveImageObject = ProductImage(id: imageId, url: imageUrl, isDefault: isDefaults)
                        imageData.append(saveImageObject)
                    }
                }
                        let saveProductObject = Product(name: productIdTitle, id: productId, images: imageData)
                        productData.append(saveProductObject)
            }
        }
    }