如何从子数组对象中检索属性值? [英] How can I retrieve a property value from child array object?

查看:47
本文介绍了如何从子数组对象中检索属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从子数组调用对象属性.在视图控制器中,类别和子类别加载了名称、路径和图像.为能够获取名称和路径但无法检索图像的子类别创建的新类.父类别返回包括图标在内的所有信息,但子类别无法获取图像.

I'm trying to call an object property from a child array. In the viewcontroller the categories and subcategories are loaded with name, path and images. A new class created for sub-categories able to get name and path but can't retreive the image. The Parent categories are returning all the info including icons however the sub-categories not able to get the image.

ViewController.swift 转场准备.

ViewController.swift segue prepare.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier! == "catalogproduct") {
        let viewController:CatalogProduct = segue.destination as UIViewController as! CatalogProduct
        viewController.productImageUrl = self.imageUrl
        viewController.productId = self.productId
        viewController.productName = self.productName
        viewController.productPrice = ""
        
    }
    if (segue.identifier! == "productcategory") {
        let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
        viewController.categoryId = categoryId
        viewController.categoryName = categoryName;
        viewController.categoryType = categoryType;
    }else if (segue.identifier! == "search") {
        let viewController:SearchSuggestion = segue.destination as UIViewController as! SearchSuggestion
        viewController.isHome = true;
    }else if (segue.identifier == "subcategory") {
        let viewController:subCategory = segue.destination as UIViewController as! subCategory
        viewController.subName = categoryName
        viewController.subId = categoryId
        viewController.subCategoryData = subCategory
    }
}

获取所有信息的类别部分

The category section getting all info

import UIKit

class CategoriesController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var cataegoriesCollectionModel = [Categories]()
@IBOutlet weak var categoriesTableView: UITableView!
var arrayForBool :NSMutableArray = [];
var categoryName:String = ""
var categoryId:String = ""
var categoryDict :NSDictionary = [:]
var subCategory:NSArray = []
var subId:String = ""
var subName:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")
        
        let image = UIImage(named: "logo.png")
        navigationItem.titleView = UIImageView(image: image)
        
        let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
        let nav1 = paymentViewNavigationController as! UINavigationController;
        let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
        cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel
        categoriesTableView.register(UINib(nibName: "CategoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        self.categoriesTableView.separatorStyle = .none
        categoriesTableView.delegate = self;
        categoriesTableView.dataSource = self;
        categoriesTableView.separatorColor = UIColor.clear
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_WIDTH / 2;
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor.white
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cataegoriesCollectionModel.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        categoriesTableView.register(UINib(nibName: "CategoryCellTableViewCell", bundle: nil), forCellReuseIdentifier: "CategoryCellTableViewCell")
         let cell:CategoriesTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoriesTableViewCell
        cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
        NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
        cell.categoryName.text = cataegoriesCollectionModel[indexPath.row].name
        
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let childrenArray = cataegoriesCollectionModel[indexPath.row].children! as NSArray;
        if childrenArray.count > 0{
            subId = cataegoriesCollectionModel[indexPath.row].id
            subName = cataegoriesCollectionModel[indexPath.row].name
            subCategory = childrenArray
            self.performSegue(withIdentifier: "subcategory", sender: self)
        }
        else{
            categoryId = cataegoriesCollectionModel[indexPath.row].id
            categoryName = cataegoriesCollectionModel[indexPath.row].name
            self.performSegue(withIdentifier: "productCategorySegue", sender: self)
        }
    }
   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "productCategorySegue") {
            let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
            viewController.categoryType = ""
            viewController.categoryName = self.categoryName
            viewController.categoryId = self.categoryId
        }else if (segue.identifier == "subcategory") {
            let viewController:subCategory = segue.destination as UIViewController as! subCategory
            viewController.subName = subName
            viewController.subId = subId
            viewController.subCategoryData = subCategory
            
        }
    }
    
}

子类别:

import UIKit


class subCategory: UIViewController,UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
    
    var cataegoriesCollectionModel = [Categories]()
    public  var subCategoryData :NSArray = []
    public var categoryName = " "
    var subCategoryMenuData:NSMutableArray = []
    var categoryId:String = " ";
    var subId:String = ""
    var subName:String = ""
    
    @IBOutlet weak var subCategoryTable: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")
        self.navigationController!.isNavigationBarHidden = false
        
        subCategoryTable.backgroundColor = UIColor().HexToColor(hexString: GREYBLACK)

        let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
        let nav1 = paymentViewNavigationController as! UINavigationController;
        let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
                cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel
        
        let childArray : NSArray? = subCategoryData
        if let itemsArray = childArray{
            for (item) in itemsArray{
                let childStoreData:NSDictionary = item as! NSDictionary;
                self.subCategoryMenuData.add(childStoreData["name"] as? String! ?? "empty");
            }
        }

        subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")

        subCategoryTable.delegate = self
        subCategoryTable.dataSource = self
        
        print(subCategoryData)
        
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ view: UICollectionView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }
    
    func collectionView(_ view: UICollectionView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SCREEN_WIDTH / 4;
    }

    func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionView, forRowAt indexPath: IndexPath) {
        cell.backgroundColor = UIColor.white
    }
    
    func collectionView(_ view: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return subCategoryMenuData.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listcollectionview", for: indexPath) as! subCategoryCollectionViewCell
        cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
        NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
        cell.categoryName.text = (subCategoryMenuData [indexPath.row] as? String)
        cell.categoryName?.textColor = UIColor().HexToColor(hexString: REDCOLOR)

        return cell;
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let childDict: NSDictionary = subCategoryData .object(at: indexPath.row) as! NSDictionary
        
        if (childDict.object(forKey: "children") as! NSArray).count > 0{
            let sb = UIStoryboard(name: "Main", bundle: nil)
            let initViewController: subCategory? = (sb.instantiateViewController(withIdentifier: "subCategory") as? subCategory)
            initViewController?.subCategoryData = (childDict.object(forKey: "children") as! NSArray)
            initViewController?.subName = childDict.object(forKey: "name") as! String!
            initViewController?.subId = childDict.object(forKey: "path") as! String!
            initViewController?.modalTransitionStyle = .flipHorizontal
            self.navigationController?.pushViewController(initViewController!, animated: true)
        }else{
            
            categoryName = childDict .object(forKey: "name") as! String
            categoryId = childDict .object(forKey: "path") as! String
            self.performSegue(withIdentifier: "productCategorySegue", sender: self)
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "productCategorySegue") {
            let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
            viewController.categoryType = ""
            viewController.categoryName = self.categoryName
            viewController.categoryId = self.categoryId
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.title = categoryName;
        self.navigationController!.isNavigationBarHidden = false
        
    }
    
}

打印的 JSON 响应:

The JSON response printed:

  categories =     (
                {
            children =             (
                                {
                    children =                     (
                                                {
                            children =                             (
                            );
                            column = 1;
                            icon = "https://example.com/image/cache/placeholder-150x150_0.png";
                            image = "https://example.com/image/categories/1.jpg";
                            name = "Subcat Name";
                            path = 1197;
                            thumb = "https://example.com/image/categories/1.jpg";
                        },

如何检索子类别的图像?

How to retrieve the image for subcategory?

推荐答案

一个快速的解决方案是传递图像 url 字符串 "https://example.com/image/categories/1.jpg" 转换为返回图像的函数:

A quick solution would be to pass the image url string "https://example.com/image/categories/1.jpg" into a function that returns an image:

同步

func imageFromURL(_ urlStr: String) -> UIImage? {
  guard 
        let url = URL(string: urlStr), 
        let data = try? Data(contentsOfUrl:url),
        let image = UIImage(data: data) 
        else {return nil}

  return image
}

同步

extension UIImageView {
   func loadImageFrom(urlString: String, mode: UIViewContentMode) {
    guard let url = URL(string: urlString) else {return}

    self.contentMode = mode

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            error == nil,
            let httpURLResponse = response as? HTTPURLResponse, 
            httpURLResponse.statusCode == 200,
            let data = data, 
            let image = UIImage(data: data)
        else { 
            return print(error?.localizedDescription ?? "Something went wrong when loading the image")
        }
        DispatchQueue.main.async { 
            self.image = image
        }
    }
    .resume()
  }
}

使用

 imageView.loadImageFrom(urlString:"https://example.com/image/categories/1.jpg", mode: .scaleAspectFit)

-

从 URL 加载图片

这篇关于如何从子数组对象中检索属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆