我正在尝试从子数组中调用对象属性。在视图控制器中,类别和子类别会加载名称,路径和图像。为子类别创建的新类能够获取名称和路径,但无法获取图像。父类别返回所有信息,包括图标,但是子类别无法获取图像。
ViewController.swift segue准备。
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
}
}
类别部分获取所有信息
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响应显示:
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";
},
任何帮助请如何检索图像的子类别,谢谢高级!
最佳答案
一种快速的解决方案是将图像url字符串“ https://example.com/image/categories/1.jpg”传递给返回图像的函数:
同步地
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)
--
请参阅链接以获取更多详细信息:
Loading Image From URL
关于ios - 如何从子数组对象中检索属性值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51662511/