问题
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:
- Check if URL is not nil when you downloading image in
cellForItemAt - Check if SDWebImage is not returning an error
sd_setImage(with: URL(string:aData.iconHome!)) { (_, error, _, _) in
if let error = error {
print(error)
}
}
- In general, try to move cell configuration inside
HomeCollectionViewCelland 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