ios - Swift:如何从 UIButton CollectionView 单元调用 json id

标签 ios json swift uicollectionviewcell

我在 UICollectionViewCell 中有一个 UIButton。想从此单元格获取 json id。我完美地解析了 UICollectionViewController 中的 json 数据。单击 UICollectionViewCell 中的 UIButton 时,我一直在结束 ID 遇到的问题。

这是我的代码

JSON

{
  "error": false,
  "product_sellers": [
    {
      "id": 5,
      "store_name": "ahmedstore",
      "photo": "user_12-06-2017-12-32-56.png",
      "is_favorite": 0
    },
    {
      "id": 122,
      "store_name": "aitldev6",
      "photo": null,
      "is_favorite": 0
    },
    {
      "id": 123,
      "store_name": "aitlmanager",
      "photo": "user_2017-08-31-10-06-am (16).jpg",
      "is_favorite": 0
    },
    {
      "id": 135,
      "store_name": "ajanta library",
      "photo": "user_2017-08-19-7-16-am23931.png",
      "is_favorite": 0
    },

Collection View Controller

类 ProductStoreCollectionViewController:UICollectionViewController,UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {

    super.viewDidLoad()


    let url = URL(string: "..........")


    URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in

        if error != nil {
            print(error ?? 0)
        }
        else {
            do {

                let items = json["product_sellers"] as? [[String: Any]] ?? []

                self.arrStore = [Store]()

                for item in items {


                    let oStore = Store()

                    oStore.id = item["id"] as? Int
                    oStore.image = item["photo"] as? String
                    oStore.store_name = item["store_name"] as? String
                    oStore.is_favorite = item["is_favorite"] as? Int

                    ProductStoreId.store_id = oStore.id!

                    self.arrStore.append(oStore)

                }

            } catch let error as NSError {
                print(error)
            }

            DispatchQueue.main.async(execute: {

                self.collectionView?.reloadData()
            })

        }



    })

UICollectionViewCell

class StoreCollectionViewCell: BaseCell{



    let heartBtn: UIButton = {

        let btn = UIButton()
        btn.setImage(UIImage(named: "heart_white_copy"), for: .normal)

        btn.translatesAutoresizingMaskIntoConstraints = false
        return btn
    }()

    var sellerId2: Int = 1


    func heartBtnClick(){

        print("box Btn click")


        self.sellerId2 = ProductStoreId.store_id


        print("add to favoriteStore\(self.sellerId2)")


    }


    override func setupCell() {

        heartBtn.addTarget(self, action: #selector(heartBtnClick), for: .touchUpInside)
        addSubview(heartBtn)




    }

}

最佳答案

这是因为您的 ProductStoreId.store_id 在您解析它时存储了最后一个 ID。

你需要在你的数据源方法中分配id

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // Your code
    let store = self.arrStore[indexPath.row] // Please correct it if not
    cell.sellerId2 = store.id
}

然后在您的 StoreCollectionViewCell 类中

func heartBtnClick(){
    print("box Btn click")
    //We don't need the below line
    //self.sellerId2 = ProductStoreId.store_id
    print("add to favoriteStore\(self.sellerId2)")
}

关于ios - Swift:如何从 UIButton CollectionView 单元调用 json id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47234690/

相关文章:

ios - 适用于 iOS 7.1 的 SKShapeNode 和 swift

ios - swift 和 sprite 工具包在屏幕上拖动手指时画一条直线

iphone - iOS Core Audio 渲染回调适用于模拟器,不适用于设备

android - 无需存储元数据的网站即可实现开放图谱的可能性,开放图谱元数据可以动态注入(inject)到 URL 中吗?

java - 以前使用的属性总是显示在 RequestBody 示例 (SwaggerUI) 和 ResponseBody(json) 中

python - 将 Spark 数据帧写为 json 数组(pyspark)

iphone - 如何让 AFHTTPRequestOperation 在完成时调用选择器,而不是 block ?

c# - 在 C# 中解析 JSON

ios - UIPageViewController/TextKit 计数页面数

ios - 如何在 swift 中暂时使我的 uiImage 变灰?