gpt4 book ai didi

ios:除 SliderCollectionViewCell 外,所有数据均从 json 网络请求加载

转载 作者:行者123 更新时间:2023-11-29 11:41:46 24 4
gpt4 key购买 nike

我在 UICollectionViewCell 中有 sliderCollectionViewController,尝试从 json web 加载数据,所有数据都没有图像加载。在这里,我喜欢在 slideCollectionViewCell 中加载图像,它在 collectionViewCell 中创建。

import UIKit

import Foundation


**DescriptionObject**

`class Description: NSObject {

var id: Int?
var product_id: Int?

var myDescription: String?
var product_description: String?

var all_images: [String]?


}

**DescriptionCollectionViewController with slideCollectionViewController**

class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{



var arrDescription = [Description]()

**json request**

func loadDescription(){

ActivityIndicator.customActivityIndicatory(self.view, startAnimate: true)


let url = URL(string: ".........")

URLSession.shared.dataTask(with:url!) { (urlContent, response, error) in
if error != nil {
print(error ?? 0)
}
else {



do {
let json = try JSONSerialization.jsonObject(with: urlContent!) as! [String:Any]




let myProducts = json["products"] as? [String: Any]

let myData = myProducts?["data"] as? [[String:Any]]



myData?.forEach { dt in

let oProduct = Description()
oProduct.id = dt["id"] as? Int
oProduct.product_id = dt["product_id"] as? Int


oProduct.myDescription = dt["description"] as? String
oProduct.product_description = dt["product_description"] as? String

if let allImages = dt["all_images"] as? [[String:Any]] {
oProduct.all_images = allImages.flatMap { $0["image"] as? String }
}



self.arrDescription.append(oProduct)
}


} catch let error as NSError {
print(error)
}
}



DispatchQueue.main.async(execute: {
ActivityIndicator.customActivityIndicatory(self.view, startAnimate: false)
self.collectionView?.reloadData()
})



}.resume()
}



fileprivate let cellId = "cellId"
fileprivate let descriptionCellId = "descriptionCellId"

override func viewDidLoad() {
super.viewDidLoad()

self.loadDescription()



collectionView?.register(DescriptionCell.self, forCellWithReuseIdentifier: descriptionCellId)
}



override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrDescription.count
}


override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: descriptionCellId, for: indexPath) as! DescriptionCell

cell.descriptionOb = arrDescription[indexPath.item]

return cell
}





**DescriptionCollectionViewCell**

class DescriptionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

var descriptionOb: Description!{
didSet{

descriptionTextView.text = descriptionOb?.myDescription

couponTextView.text = descriptionOb?.product_description

slideCollectionView.reloadData()
}
}

override init(frame: CGRect) {
super.init(frame: frame)



setupCell()


}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}




let descriptionTextView: UITextView = {


let textview = UITextView()

textview.text = "Description is the pattern of development "


return textview
}()



let couponTextView: UITextView = {

let textview = UITextView()

textview.text = "Description is the pattern of development "

return textview
}()



fileprivate let cellId = "cellId"

lazy var slideCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.clear
return cv
}()



func setupCell() {



slideCollectionView.dataSource = self
slideCollectionView.delegate = self

slideCollectionView.isPagingEnabled = true




slideCollectionView.register(SlideCell.self, forCellWithReuseIdentifier: cellId)

addSubview(slideCollectionView)




addSubview(descriptionTextView)


addSubview(couponTextView)



}




func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let count = descriptionOb?.all_images?.count{
return count
}
return 0
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideCell


if let imageName = descriptionOb?.all_images?[indexPath.item] {
cell.imageView.image = UIImage(named: imageName)
}

return cell
}


}


**SlideCollectionViewCell**

class SlideCell: UICollectionViewCell{




override init(frame: CGRect) {
super.init(frame: frame)



setupCellSlider()


}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

let imageView: CustomImageView = {
let iv = CustomImageView()
iv.contentMode = .scaleAspectFill
iv.image = UIImage(named: "defaultImage3")
iv.backgroundColor = UIColor.green
return iv
}()




func setupCellSlider() {


backgroundColor = .green



addSubview(imageView)


}



}`

**Image Extension**

let imageCache = NSCache<AnyObject, AnyObject>()

class CustomImageView: UIImageView {

var imageUrlString: String?

func loadImageUsingUrlString(_ urlString: String) {

imageUrlString = urlString

guard let urlEncoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
print("Encoding not done")
return
}

let url = URL(string: urlEncoded)

image = nil

if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}


if let url = url {
URLSession.shared.dataTask(with: url, completionHandler: {(myData, respones, error) in

if error != nil {
print(error ?? 0)
return
}

if let myData = myData {
DispatchQueue.main.async(execute: {

let imageToCache = UIImage(data: myData)

if self.imageUrlString == urlString {
self.image = imageToCache
}

if let imageToCache = imageToCache {
imageCache.setObject(imageToCache, forKey: urlString as AnyObject)
}
})
}

}).resume()
}
}

}

json 网络数据

enter image description here

最佳答案

您应该使用 UIImageView 子类 CustomImageView 中的方法

所以代替

cell.imageView.image = UIImage(named: imageName)

试试这个:

cell.imageView.loadImageUsingUrlString(imageName)

DescriptionCellcellForItem 方法中

关于ios:除 SliderCollectionViewCell 外,所有数据均从 json 网络请求加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46147791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com