Как выдвинуть другой контроллер представления из представления коллекции didSelectItemAt на основе идентификатора Json в swift - PullRequest
1 голос
/ 28 сентября 2019

Мой проект содержит collectionView .. но как выдвинуть другой viewcontroller из didSelectItemAt на основе идентификатора json .. и у меня есть отдельные vewcontroller для каждого идентификатора .., но я не могу выдвинуть различные viewcontrolls с didSelectItemAt на основе идентификатора json.

вот мой Json для collectionView:

{
"financer": [
    {
        "id": "45",
        "icon": "https://hello.com//images/img1.png"
    }
    {
        "id": "40",
        "icon": "https://hello.com//images/img2.png"
     }
     .
     .
     .
   ]
 }

вот мой домашний код collectionview:

import UIKit

struct JsonData {

var iconHome: String?
init(icon: String, tpe: String) {
    self.iconHome = icon
}
}

class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var collectionView: UICollectionView!

var itemsArray = [JsonData]()
var idArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()

    homeServiceCall()
    //Do any additional setup after loading the view.
    collectionView.delegate = self
    collectionView.dataSource = self
}

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

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell

    let aData = itemsArray[indexPath.row]
    cell.paymentLabel.text = aData.typeName

    if let url = NSURL(string: aData.iconHome ?? "") {
        if let data = NSData(contentsOf: url as URL) {
            cell.paymentImage.image = UIImage(data: data as Data)
        }
    }
    return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
    self.navigationController?.pushViewController(nextViewController, animated: true)
    let indexPathHome = indexPath.row
    print("home collectionItem indexpath \(indexPathHome)")

}

//MARK:- Service-call

func homeServiceCall(){

    let urlStr = "https://dev.com/webservices/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        guard let respData = data else {
            return
        }

        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            let financerArray = jsonObj["financer"] as! [[String: Any]]

            for financer in financerArray {

                let id = financer["id"] as! String
                let pic = financer["icon"] as? String
                print("home financer id \(id)")
                self.idArray.append(id)
                print("the home financer idsArray \(self.idArray.append(id))")
                self.itemsArray.append(JsonData(icon: pic ?? ""))
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        catch {
            print("catch error")
        }

    }).resume()
}
}

когда я нажимаю на любой элемент из collectionview, я могу нажать то же самоеКонтроллер представления, но мне нужно нажать другой контроллер представления на основе идентификатора JSON.я не знаю, как и где использовать JSON ID для проталкивания различных viewcontroller с помощью didselectItem atIndexPath.кто-нибудь, пожалуйста, помогите мне здесь.

1 Ответ

2 голосов
/ 28 сентября 2019

Обновите вашу homeServiceCall функцию

func homeServiceCall(){

    let urlStr = "https://dev.com/webservices/getfinancer"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in

        guard let respData = data else {
            return
        }

        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            let financerArray = jsonObj["financer"] as! [[String: Any]]

            for financer in financerArray {

                let id = financer["id"] as! String
                let pic = financer["icon"] as? String

                self.itemsArray.append(JsonData(icon: pic ?? ""))
                self.idArray.append(id)
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        catch {
            print("catch error")
        }

    }).resume()
}

Создайте строковое свойство с именем financerId в вашей MakePaymentViewController

В вашей didSelect функции

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as? MakePaymentViewController {
        nextViewController.finacerId = idArray[indexPath.row]
      self.navigationController?.pushViewController(nextViewController, animated: true)
    }

}

Обновление

for financer in financerArray {
      if let id = financer["id"] as? Int {
          self.idArray.append(id)
      }

      if let pic = financer["icon"] as? String {
          elf.itemsArray.append(JsonData(icon: pic))
      }
}
...