Как отобразить домашний просмотр таблицы только для выбранного массива элементов индекса в следующем просмотре таблицы управления в Swift - PullRequest
1 голос
/ 31 октября 2019

У меня есть home collectionView, здесь, если я щелкну один элемент, используя didSelectItemAtindexPathin в доме, этот массив значений элементов должен отображаться в табличном представлении AllMakePaymentViewController. но здесь я получаю все значения домашних элементов в AllMakePaymentViewController ... но как показать только значения элементов, выбранных нажатием, в табличном представлении AllMakePaymentViewController. для того же typename есть как в home, так и в AllMakePaymentViewController json .. Пожалуйста, помогите мне в коде.

вот мой код для homeVC:

import UIKit
import SDWebImage
struct JsonData {
var iconHome: String?
var typeName: String?
var id: String?
init(icon: String, tpe: String, id: String) {
    self.iconHome = icon
    self.typeName = tpe
    self.id = id
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate {

@IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
var typeName: String?
var saveTypenameKey: String?

override func viewDidLoad() {
    super.viewDidLoad()
    homeServiceCall()
}
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
    cell.paymentImage.sd_setImage(with: URL(string:aData.iconHome ?? ""), placeholderImage: UIImage(named: "varun finance5_icon"))
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if itemsArray[indexPath.item].typeName == "WATER"{
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
        self.navigationController?.pushViewController(nextViewController!, animated: true)
    }
    else if itemsArray[indexPath.item].typeName == "ELECTRICITY"{
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
        self.navigationController?.pushViewController(nextViewController!, animated: true)
    }
    else if itemsArray[indexPath.item].typeName == "CASH POINT"{
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
        self.navigationController?.pushViewController(nextViewController!, animated: true)
    }
    else if itemsArray[indexPath.item].typeName == "DTH"{
        let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
        self.navigationController?.pushViewController(nextViewController!, animated: true)
    }
    else{
        AlertFun.ShowAlert(title: "", message: "will update soon..", in: self)
    }
}
//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
        }
        guard error == nil else {
            print("error")
            return
        }
        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            //print("the home json is \(jsonObj)")
            let financerArray = jsonObj["financer"] as! [[String: Any]]

            for financer in financerArray {
                let id = financer["id"] as? String
                let pic = financer["icon"] as? String
                self.typeName = financer["tpe"] as! String
                KeychainWrapper.standard.set(self.typeName!, forKey: "typeName")
                print("keychain typename \(KeychainWrapper.standard.set(self.typeName!, forKey: "typeName"))")
                self.itemsArray.append(JsonData(icon: pic ?? "", tpe: self.typeName ?? "", id: id ?? ""))
            }
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
        catch {
            print("catch error")
        }
    }).resume()
}
}

Это мой код AllMakePaymentViewController:

class PaymentTableViewCell: UITableViewCell{
@IBOutlet weak var pamntTypeLabel: UILabel!
}

class AllMakePaymentViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!
var categoryName: String?
var iteamsArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    allPaymentService()
}
func allPaymentService(){

    let urlStr = "https://dev.com/webservices/api.php?rquest=billermdm"
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        guard let respData = data else {
            return
        }
        guard error == nil else {
            print("error")
            return
        }
        do{
            let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
            //print("the all make payment json is \(jsonObj)")
            let billerdetailsArray = jsonObj["billerdetails"] as! [[String: Any]]

            for billerdetail in billerdetailsArray {

                self.categoryName = billerdetail["bcategoryname"] as? String

                if self.categoryName == "Water"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                }
                if self.categoryName == "Electricity"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                }
                if self.categoryName == "CashPoin"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                }
                if self.categoryName == "DTH"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                }
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        catch {
            print("catch error")
        }
    }).resume()
}
}

extension AllMakePaymentViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if categoryName == "Water"{
        return iteamsArray.count
    }
    if categoryName == "Landline Postpaid"{
        return iteamsArray.count
    }
    if categoryName == "DTH"{
        return iteamsArray.count
    }
    if categoryName == "Electricity"{
        return iteamsArray.count
    }
    return iteamsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell
    cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
    self.tableView.separatorStyle = .none
    return cell
}
}

здесь достаточно только одного itemsArray или я возьму другой массив для различных категорий, таких как electrictyArray, waterArray ... потому что здесь я получаю все значения в tabelview ... мне нужно тольконажал домашний элемент valuesarray .. Пожалуйста, помогите мне в коде

1 Ответ

0 голосов
/ 31 октября 2019

Вам нужно установить переменную в nextViewController, прежде чем помещать ее в стек (и вы должны использовать if let, чтобы избежать возможных сбоев):

    if let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController {
        // set the var in the new view controller
        nextViewController.categoryName = "WATER"
        // now push it onto the stack
        self.navigationController?.pushViewController(nextViewController, animated: true)
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...