问题与传递适当的图像到tableviewcell

这是我的结构…

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上,点击一个button,我想把这个图像传递给tableviewcellcollectionview确实有一些标签,名称和id已经成功传递了…但是如何传递图片,我无法弄清楚。 以下是点击销售button发生的事情…

 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中的图像和其他数据。 这是cellForRow ..(从单元格被加载的tableview的代码)

 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. ie 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]创build一个数组types,并使用默认的初始化程序进行粘贴。

 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]? } 

ControllerClass(具有获取初始数据的集合视图) – :

在你的控制器类中,我创build了2个数组 – :

1)保存图像的数据。

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

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

1)保持图像对象数据。

2)ProductObject数据。

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一个button时,获取tapped索引,并从Product数组中读取该索引处的Product对象。之后,可以轻松地将所需数据传递给表视图(Second class)。

第二个控制器类:

  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 } } 

一旦您在第二课中获得了图片URL和其他所需的信息,您就可以轻松地将其呈现在桌面上。 获取图像使api call 服务器 。 我希望能帮到你。

代码parsing – :

 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) } } }