【问题标题】:Issue with passing proper image to tableviewcell将正确的图像传递给 uitableviewcell 的问题
【发布时间】:2017-10-23 09:17:35
【问题描述】:

这是我的结构...

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 中分配图像和其他数据的方式。这是 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. 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
    }
}

【问题讨论】:

    标签: ios swift uiviewcontroller uicollectionview swift-structs


    【解决方案1】:

    结构为您提供了明智的初始化程序,因此在大多数情况下您不需要自己的初始化程序。在您的代码中,您的产品初始化程序仅包含名称和 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]?
    }
    

    ControllerClass(通过集合视图获取初始数据)-:

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

    1) 保存图像数据。

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

    为了保存数据,我现在只是传递常量值。在viewDidLoad 中,我为每个对象调用了初始化程序-:

    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 时,获取点击的索引,并从 Product 数组中读取该索引处存在的产品对象。之后,您可以轻松地将所需的数据传递给表视图(第二类)。

    第二个控制器类-:

     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 发送到服务器。我希望这对你有帮助。

    解析代码-:

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

    【讨论】:

    • @bws 是的。
    • .@Tushar Sharma 确实尝试了您的方法。但这似乎不起作用。您的方法似乎与我所做的不同……我确实尝试将您的建议采用到我已有的方法中,但没有奏效。您能否建议任何替代方法将正确的图像传递给 tableviewcell..?
    • @bws 您面临的问题是什么?你能用你尝试的方法更新你的代码吗?
    • 问题是……selectedItems 数组包含所有结构元素。所以即使图像也必须添加到这个数组中。一旦我们能够做到这一点,我认为这个问题可以得到解决。但是我无法弄清楚如何实现这一点..
    • 当你的集合类加载数据时,你可以很容易地做到这一点,然后点击收集单元格,只需从产品数组中读取点击的单元格索引,并在该索引处获取适当的产品对象((也将具有该索引的图像 url)),一旦你将所需的数据传递给第二个控制器。您不能直接传递图像,您需要将名称或网址保存为字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多