首页 > 解决方案 > 如何快速在collectionView中添加图像

问题描述

我有带有图像的collectionview ..

如果我在其中提供占位符图像,sd_setImage那么我将在 collectionview 中获取该图像,否则它在 collectionview 中将为零,为什么?完美地我得到了所有图像,cellForItemAt然后为什么我无法在collectionview屏幕中显示它。

我在代码中犯错的地方。请在我的代码中帮助我。

这是我的代码:

 import UIKit
 import SDWebImage 

 struct JsonData {
   var iconHome: String?
   var typeName: String?
   init(icon: String, tpe: String) {
     self.iconHome = icon
     self.typeName = tpe
   }
}

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {

  @IBOutlet weak var collectionView: UICollectionView!

  var itemsArray = [JsonData]()

  override func viewDidLoad() {
    super.viewDidLoad()

    homeServiceCall()
  }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return itemsArray.count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

    let aData = itemsArray[indexPath.row]
    cell.paymentLabel.text = aData.typeName
    cell.paymentImage.sd_setImage(with: URL(string:aData.iconHome!), placeholderImage: UIImage(named: "home_icon"))

    print("tableview collection images \(String(describing: aData.iconHome))")
    return cell
  }

//MARK:- Service-call

  func homeServiceCall(){

    let urlStr = "https://com/webservices/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

       guard let respData = data else {
          return
       }
       guard error == nil else {
          print("error")
          return
       }
       do{
          let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
          //print("the home json is \(jsonObj)")
          let financerArray = jsonObj["financer"] as! [[String: Any]]
          print("home financerData \(financerArray)")

          for financer in financerArray {

             let id = financer["id"] as? String
             let pic = financer["icon"] as? String
             let typeName = financer["tpe"] as! String

             print("the icons \(String(describing: pic))")
             self.itemsArray.append(JsonData(icon: pic ?? "", tpe: typeName))
          }

          DispatchQueue.main.async {
             self.collectionView.reloadData()
          }
     }
     catch {
        print("catch error")
     }

  }).resume()
 }
}

标签: iosjsonswiftuicollectionviewuiimageview

解决方案


我建议您使用Lottie为您节省大量代码行


推荐阅读