无法将正确的图像传递给tableviewcell

时间:2017-10-17 06:13:57

标签: ios swift uitableview uicollectionview

我有两个结构如下:

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,里面有一些单元格,每个单元格都有一个图像,一个名称标签和一个id标签。它还有一个按钮,当我点击它时,collectionview单元格上的图像以及名称和id显示在tableviewcell中并存储在一个数组中。返回并单击第二个collectionview项目的按钮后,我现在将看到2个单元格。(第1个和第2个)。我这样做......

func SellBtnTapped(_ sender: UIButton) {

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

   self.photoThumbnail = self.arrayOfURLImages[(indexPath?.row)!]

   let myVC = storyboard?.instantiateViewController(withIdentifier: "productSellIdentifier") as! sellTableViewController

   let productObject = productData1[(indexPath?.row)!]

        if selectedItems == nil {
          selectedItems = [Product(name:productObject.name, id: productObject.id)]

        } else {
            selectedItems?.append(productObject)

         }
      myVC.arrProduct = selectedItems
        navigationController?.pushViewController(myVC, animated: true) }

但我的问题是我无法传递正确的图像,就像我的名字和身份证一样。在我的情况下,名称&传递的id是正确的,但传递的图像是错误的。我该如何修理它??

编辑:将图像和其他数据都添加到数组中的json解析如下所示

     var theProduct = Product(name: name, id: id, theRate: rate, quantity: qty, sku: skuCode, prdCateg: prodCat, prodDescr: description)
     if let images = anItem["product_images"] as? [[String:String]] {
     for image in images {
     guard let imageId = image["id"],
     let url1 = image["image"],
     let isDefault = image["is_default"] else {continue}
     print(imageId)
     let productImage = ProductImage(id: imageId, url: URL(string: url1)!, isDefault: isDefault == "1")
     theProduct.add(image: productImage) //image is added here
     self.productData1.append(theProduct)

     let url = URL(string: url1)
     let data = try? Data(contentsOf: url!)
     self.arrayOfURLImages.append(UIImage(data: data!)!)
     self.appDelegate.commonArrayForURLImages = self.arrayOfURLImages

编辑2:

这就是我在tableviewcell中分配图像和其他数据的方式。这是cellForRow的代码..(从中加载单元格的tableview)。

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

 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
    }

1 个答案:

答案 0 :(得分:1)

我认为问题是异步加载的图像, 下载图像需要一些时间,下载后可能会将错误的图像分配给单元格。

试试这个https://github.com/onevcat/Kingfisher