首页 > 解决方案 > 如何在swift中的下一个viewcontroll tableview中仅显示主tableview选定的索引项数组计数

问题描述

我有 home collectionView,如果我在 home 中使用 didSelectItemAtindexPathin 单击一个项目,则项目值数组需要显示在 AllMakePaymentViewController tableview 中。但在这里我在 AllMakePaymentViewController 中获取所有家庭项目值...但是如何在 AllMakePaymentViewController 表视图中仅显示单击的项目值。对于 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 就足够了,或者我应该从不同类别的不同类别中获取 diierent 数组,如 ElectrictyArray、waterArray ......因为这里我在 tableview 中获取所有值......我只需要点击主页项目 valuesarray ..请在代码中帮助我

标签: iosarraysjsonswiftuitableview

解决方案


您需要在将 varnextViewController推入堆栈之前对其进行设置(您应该使用它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)
    }

推荐阅读