ios - 如何快速在collectionView中添加图像
问题描述
我有带有图像的collectionview ..
如果我在其中提供占位符图像,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()
}
}
解决方案
我建议您使用Lottie为您节省大量代码行
推荐阅读
- c# - 使用进度条生成 RSA 密钥
- c# - Microsoft 标识平台和 ASP.NET Core 标识之间有什么区别?
- cassandra - Cassandra - 以下查询的最佳表建模?
- python - ProgressBar2 在 PyCharm 中无法正常工作
- java - 如何通过(tab)读取csv文件并通过java将文件存储到arraylist
- javascript - 具有两个参数的乘法函数并将结果加 100
- python - TypeError:无法将“时间戳”类型与“int”类型进行比较
- visual-studio-2019 - Visual Studio 2019 中的“条件生成符号”选项在哪里
- react-native - 管理数据中的搜索反应原生
- python - 在 python 中绘制 3D 等值面