ios - Swift:除了图像之外,所有内容都从 web 加载到 collectionViewCell 中

标签 ios json swift swift3 uicollectionview

我在 UICollectionViewCell 中放置了一个 sliderCollectionViewController,现在所有内容都可以从网络正确加载,无需图像。但我没有收到任何有关错误的消息

import UIKit
import Foundation

NSObject

class Description: NSObject {

    var id: Int?
    var product_id: Int?        
    var myDescription: String?      
    var all_images: [String]?    
    var product_description: String?      
}

DescriptionCollectionViewController

class DescriptionCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout{

    var arrDescription = [Description]()

    ** Networking Request api **

    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

                        oProduct.all_images = dt["all_images"] 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()
    }


    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
        }
    }

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

        setupCell()
    }

    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
    }()


        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
        }()

    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
    }
}

slider 单元

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)        
    } 
}

json 网络 enter image description here

最佳答案

问题是你做了:

                oProduct.all_images = dt["all_images"] as? [String]

但是 all_images 不是一个字符串,它是一个字典,正如您在 json 中看到的那样。

您必须访问 all_images 的关键图像才能正确显示它。

看这个: How to access deeply nested dictionaries in Swift

你可以试试这个:

                oProduct.all_images = dt["all_images"]["image"] as? [String]

关于ios - Swift:除了图像之外,所有内容都从 web 加载到 collectionViewCell 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46138325/

相关文章:

ios - Xcode 12 模拟器崩溃

iphone - 如何在iPhone中关闭UIView,如“Skype或任何窗口”最小化?

ios - 执行相互调用的方法。全部在后台

ios - 在 Swift/Objc 混合项目中关闭模态 Controller 触发的 Segue

android - obj.getJSONArray 未获取 JSON 响应

arrays - 排序数组和查找更改 - Swift

c++ - Opencv - 如何获取图像中存在的垂直线数(线数)

ios - UIlabel layer.cornerRadius 在 iOS 7.1 中不起作用

java - 为此用例选择最高效的 JSON 库

jquery - Perl:如何包含使用 ajax/json 传递的 DBIx::Class 查询信息的标量引用