我有带有图像的 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()
}
}
最佳答案
- 在
cellForItemAt
中下载图片时检查 URL 是否不为零 - 检查 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/