2017-09-11 36 views
1

我有sliderCollectionViewControllerUICollectionViewCell,尝试从json web加载数据,所有数据加载没有图像。在这里,我喜欢加载在collectionViewCell中创建的slideCollectionViewCell中的图像。ios:所有数据从json web请求加载除了SliderCollectionViewCell

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

+0

方法如果加上'descriptionOb .all_images'之前'如果let'然后它打印的图像串与否? – 3stud1ant3

+0

@ 3stud1ant3它必须放置在'DescriptionCell'类的'cellForItemAt'方法的哪个部分 –

+0

您正在设置图像 – 3stud1ant3

回答

1

你应该UIImageViewCustomImageView

使用方法,以便代替

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

试试这个:

cell.imageView.loadImageUsingUrlString(imageName) 

cellForItemDescriptionCell