如何在collectionView中添加json图像,而不会迅速添加nil

问题描述 投票:0回答:2

我具有图像的collectionview。我正在从json和cellForRowAt,但是为什么我不能在collectionview中显示图像。

如果我在sd_setImage中提供占位符图像,那么我将在collectionview中获得该图像,否则它将在collectionview中显示为nil,为什么?完美地我在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()
}
}

[我有图像的collectionview。我从json和cellForRowAt获取所有图像,但是为什么我不能在collectionview中显示图像。如果我在sd_setImage中提供占位符图像,那么我就是...

ios json swift uicollectionview uiimageview
2个回答
0
投票
    [在cellForItemAt中下载图像时检查URL是否不为零

0
投票
我建议您使用Lottie来节省很多代码行
© www.soinside.com 2019 - 2024. All rights reserved.