【问题标题】:Why i am not able to delete one more CollectionVIew Cell with JSON parameter in swift?为什么我无法在 swift 中使用 JSON 参数再删除一个 CollectionVIew Cell?
【发布时间】:2021-04-03 16:34:52
【问题描述】:

在我的视图控制器中,我有两个 JSON API 1) 用于将图像和标题添加到 collectionView 单元格和 2) 用于删除单元格

使用下面的代码我第一次只能删除一个单元格,如果我尝试删除另一个我无法删除的单元格,.. 我收到 json 验证错误,为什么?.. 我想随时删除选定的单元格..

这是我的第一个 JSON API 响应:用于将图像和标题添加到 collectionview... 与此相应的 pic_id 我需要在我的第二个 JSON API 中删除单元格..

  {
"jsonrpc": "2.0",
"result": {
    "image": {
        "image": "1616588156.jpg",
        "image_title": "City",
        "user_id": 2,
        "updated_at": "2021-03-24 17:45:56",
        "created_at": "2021-03-24 17:45:56",
        "pic_id": 14
    },
    "message": "Image uploaded Successfully!"
 }
 }

上述 JSON 服务的代码以将图像和标题添加到 collectionview.. 这里我将 pic_id 保存在 UserDefaults UserDefaults.standard.set(picId, forKey: "pic_id") 中,就像这样

   fileprivate func postServiceCall(){
    
   if titleTextfield.text?.trim() == ""{
   return self.view.makeToast("please add service title")
   }
    let parameters = ["image_title" : titleTextfield.text?.trim() ?? ""]
    
    APIReqeustManager.sharedInstance.uploadMultipartFormData(param: parameters, url: CommonUrl.edit_profile_images, image: imageProfile, fileName: "image", vc: self, isHeaderNeeded: true) {(responseData) in
        print("edit profile result \(responseData)")
            if let result = responseData.dict?["result"] as? NSDictionary{
                    let success = result["status"] as? [String : Any]
                    let message = success?["message"] as? String
                if message == "Success"{
                    let image = result["image"] as? [String : Any]
                    let picId = image?["id"]
                    UserDefaults.standard.set(picId, forKey: "pic_id")// here i am saving pic_id
                    self.arrImageItems.append(ImageItemModel(title: self.titleTextfield.text, imgTitle: self.imageProfile))
                    self.collectionView.reloadData()
                }
                else{
                    self.view.makeToast(CommonMessages.somethingWentWrong)
                }
            }
        }
    }

集合视图中移除单元格的 JSON 服务代码

@objc func deleteService(sender:UIButton) {
    let picId = UserDefaults.standard.string(forKey: "pic_id")
    print("selected picid \(picId)")
    let param = ["pic_id" : picId]
    APIReqeustManager.sharedInstance.serviceCall(param: param as [String : Any], method: .post, loaderNeed: false, loadingButton: sender as! TransitionButton, needViewHideShowAfterLoading: nil, vc: self,?url: CommonUrl.edit_profile_images_remove, isTokenNeeded: true, isErrorAlertNeeded: true, isSuccessAlertNeeded: false, actionErrorOrSuccess: nil, fromLoginPageCallBack: nil) { [weak self] (resp) in
            if let code = ((resp.dict?["result"] as? [String : Any])){
                print("total result: \(code)")
                let success = code["status"] as? [String : Any]
                let message = success?["message"] as? String
                if message == "Success"{
                    let selectedIndex = sender.tag
                    self?.arrImageItems.remove(at: selectedIndex)
                    self?.collectionView.reloadData()                    }
            }else{
                self?.view.makeToast(CommonMessages.somethingWentWrong)
            }
        }
}

这是collectionview cellForItemAt 代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
    cell.imgView.image = arrImageItems[indexPath.item].profileImage
    cell.lblTitle.text = arrImageItems[indexPath.row].title
    cell.deleteButton.tag = indexPath.row
    cell.deleteButton.addTarget(self, action: #selector(deleteService(sender:)), for: UIControl.Event.touchUpInside)

    return cell
}

这是ImageItemModel 模型

class ImageItemModel{
var title: String?
var profileImage: UIImage?
var pic_id: String?

init(title: String?, imgTitle: UIImage?, pic_id: String?) {
    self.title = title
    self.profileImage = imgTitle
    self.pic_id = pic_id
}
}

使用上面的代码,我只能第一次删除一个单元格..如果我试图再删除一个单元格,那么我会收到 JSON 验证错误...如何一直删除选定的单元格..请这样做代码帮助

【问题讨论】:

  • 能把cellforItem的代码发到indexPath吗?
  • @Zain 我已经添加了代码.. 请指导我

标签: json swift uicollectionview


【解决方案1】:

您在用户默认值中存储具有相同键的图片,这是错误的。它只会存储循环的最后一项。 您应该像这样在 postServiceCall 方法中的模型中添加 picID

self.arrImageItems.append(ImageItemModel(title: self.titleTextfield.text, imgTitle: self.imageProfile, picID: picId))

然后在 deleteService 方法中你需要像这样获取 picID

let picId = UserDefaults.standard.string(forKey: "pic_id")//Replace this with this one
let picId = arrImageItems[sender.tag]. picID

现在一切都会好起来的。

【讨论】:

  • @learn_swift 我已经更新了我的答案,请检查。抱歉,我没有注意到您正在使用 userdefault。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多