如何在CollectionView中快速添加图像 [英] How to add images in collectionView in swift
本文介绍了如何在CollectionView中快速添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有图像的收藏夹视图.
I have collectionview with images..
如果我在sd_setImage
中提供占位符图像,则我在collectionview中获得该图像,否则它在collectionview中显示为nil,为什么?
完全可以在cellForItemAt
中获取所有图像,然后为什么我无法在collectionview屏幕中显示它.
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.
这是我的代码:
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()
}
}
推荐答案
我建议您使用 Lottie 来为您节省很多代码行
I would suggest you to use Lottie to save you lots of lines of codes
这篇关于如何在CollectionView中快速添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文