ios - 如何快速在collectionView中添加图像

标签 ios json swift uicollectionview uiimageview

我有带有图像的 Collection View ..

如果我在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()
 }
}

最佳答案

  1. cellForItemAt 中下载图片时检查 URL 是否不为零
  2. 检查 SDWebImage 是否未返回错误
        sd_setImage(with: URL(string:aData.iconHome!)) { (_, error, _, _) in
            if let error = error {
                print(error)
            }
        }
  • 一般来说,尝试在 HomeCollectionViewCell 内移动单元格配置,并且不要忘记添加
  •     override func prepareForReuse() {
            super.prepareForReuse()
            reviewerImage.sd_cancelCurrentImageLoad()
        }
    

    关于ios - 如何快速在collectionView中添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292027/

    相关文章:

    ios - 在 iOS 上更新 map 样式时白色闪烁

    ios - UICollectionViewCell 背景图像超出单元格

    java - Http Post的响应代码是415。如何使响应代码为200

    c# - Newtonsoft Json反序列化为具有 bool 属性的动态列表变成字符串

    swift - 试图让 API/URL 显示在我的 UILabel 文本中?

    ios - 将 UIFont 存储为 NSDictionary?

    ios - NSTimer 不会在 React Native 组件中触发

    android - 通过 Web 服务将数据从 Android 应用程序输入数据库

    swift - 命令因信号 : Segmentation fault: 11 Xcode 7 而失败

    swift - 具有扩展所使用的通用类型别名的协议(protocol)