How to add images in collectionView in swift

放肆的年华 提交于 2019-12-13 03:09:20

问题


I have collectionview with images..

if i give placeholder image in sd_setImage then i am getting that image in collectionview, otherwise it shoes nil in collectionview why?? perfectly I'm getting all images in cellForItemAt then why i am unable to display it in collectionview screen.

where i did mistake in my code. please help me in my code.

here is my code:

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

回答1:


  1. Check if URL is not nil when you downloading image in cellForItemAt
  2. Check if SDWebImage is not returning an error
        sd_setImage(with: URL(string:aData.iconHome!)) { (_, error, _, _) in
            if let error = error {
                print(error)
            }
        }
  1. In general, try to move cell configuration inside HomeCollectionViewCell and dont forget to add
    override func prepareForReuse() {
        super.prepareForReuse()
        reviewerImage.sd_cancelCurrentImageLoad()
    }



回答2:


I would suggest you to use Lottie to save you lots of lines of codes



来源:https://stackoverflow.com/questions/58292027/how-to-add-images-in-collectionview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!