如何在 swift 的 tableview 的 numberOfRowsInSection 中比较和显示不同的数组计数

How to compare and display different array count in numberOfRowsInSection in tableview in swift

我有带标签的表视图,我需要在表视图中针对不同的类别显示不同的数组计数。为此,我为不同的类别采用了不同的数组,但我无法检查条件,条件一直在 return 计数 numberOfRowsInSection 中,我在 tableview 中获取所有类别值。 我必须将 homeVC typeName 与 AllMakePaymentViewController 类别名称进行比较,并相应地显示在 tableview 中。

用于在 AllMakePaymentViewController 表视图中保存类别值的 HomeVC 代码和 selecting 类型:

 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{
    AlertFun.ShowAlert(title: "", message: "will update soon..", in: self)
}
}

 //MARK:- Service-call
  func homeServiceCall(){

    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")
            var saveTypenameKey = KeychainWrapper.standard.string(forKey: "typeName")
            print("keychain typename \(KeychainWrapper.standard.set(self.typeName!, forKey: "typeName"))")
            self.itemsArray.append(JsonData(icon: pic ?? "", tpe: self.typeName ?? "", id: id ?? ""))
        }
    }
    catch {
        print("catch error")
    }
}).resume()
}

AllMakePaymentViewController代码:

import UIKit

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

class AllMakePaymentViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!
var electricityArray = [String]()
var waterArray = [String]()
var iteamsArray = [String]()

var categoryName: 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.waterArray.append(bName ?? "")
                }
                if self.categoryName == "cashpoint"{
                    let bName = billerdetail["bname"] as? String
                    self.iteamsArray.append(bName ?? "")
                }
                if self.categoryName == "Electricity"{
                    let bName = billerdetail["bname"] as? String
                    self.electricityArray.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 waterArray.count
    }
    if categoryName == "cashpoint"{
        return iteamsArray.count
    }
    if categoryName == "Electricity"{
        return electricityArray.count
    }
    return iteamsArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell

    if categoryName == "Electricity"{
        cell.pamntTypeLabel.text = electricityArray[indexPath.row]
    }
    if categoryName == "Water"{
        cell.pamntTypeLabel.text = waterArray[indexPath.row]
    }
    if categoryName == "cashpoint"{
        cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
    }
    else
    {
        cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
    }
    self.tableView.separatorStyle = .none

    return cell
}
}

如何将 didselectItematIndex 中的 homeVC typeName select 与 AllMakePaymentViewController 类别名称进行比较,并在表格视图标签中仅显示 selected 项目类别名称值。请在上面的代码中帮助我。我被困在这里很久了。

您需要将类别顶部注入到 nextViewControllers 中,以便它知道要显示的数据。为了尽量减少字符串文字的使用,我将它们转换为一个枚举,并更改了代码以改为使用它。

enum Category: String {
  case water = "WATER"
  case electricity = "ELECTRICITY"
  case cashpoint = "CASHPOINT"
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "AllMakePaymentViewController") as? AllMakePaymentViewController
  switch Category(rawValue: [indexPath.item].typeName) {
    case .water: nextViewcontroller.category = .water
    case .electricity: nextViewcontroller.category = .electricity
    case .cashpoint: nextViewcontroller.category = .cashpoint
    default: AlertFun.ShowAlert(title: "", message: "will update soon..", in: self)
  }
  self.navigationController?.pushViewController(nextViewController!, animated: true)
}
class AllMakePaymentViewController: UIViewController {

  @IBOutlet weak var tableView: UITableView!
  var electricityArray = [String]()
  var waterArray = [String]()
  var iteamsArray = [String]()

  var category: Category?

  //load data etc
}

extension AllMakePaymentViewController: UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  guard let category = category else {return 0}
  switch category {
    case .electricity: return electricityArray.count
    case .water: return waterArray.count
    case .cashpoint: return iteamsArray.count
  }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! PaymentTableViewCell

  guard let category = category else {return 0}
  switch category {
    case .electricity: cell.pamntTypeLabel.text = electricityArray[indexPath.row]
    case .water: cell.pamntTypeLabel.text = waterArray[indexPath.row]
    case .cashpoint: cell.pamntTypeLabel.text = iteamsArray[indexPath.row]
  }
    self.tableView.separatorStyle = .none
    return cell
  }
}

注意:无法编译此文件,因此可能存在小错别字,但它应该为您提供所需内容的基础。询问 XCode 是否抛出任何语法错误。