TableView Cell Swift4中的CollectionView

时间:2018-07-16 04:03:15

标签: tableview swift4 collectionview

我在tableView内创建了一个collectionView,并以JSON格式获取了数据。在每个tableview单元格中,有collectionviewcell的数组,其数量有所不同,但出现了相同的collectionviewcell。请帮助我对此感到困惑。 这是我的编码:

ViewController.swift类

import UIKit

struct ModelPurchaseRequest {

    var year: String
    var type: String
    var listFlowStatus: [String]
    var listFlowPosition: [String]

    init(year: String, type: String, listFlowStatus: [String], listFlowPosition: [String]) {
        self.year = year
        self.type = type
        self.listFlowStatus = listFlowStatus
        self.listFlowPosition = listFlowPosition
    }

}

var listFlowStatus = [String]()
var listFlagPosition = [String]()
var modelPurchase = [ModelPurchaseRequest]()

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    var flowStatus = ""
    var flagPosition = ""

    var purYear = ""
    var purType = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        getDataPurchaseRequest()
    }

    func getDataPurchaseRequest() {

        let url = URL(string: "https://xxxxxxxxxxxxxx")

        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print("Get list purchase request error")
                return
            }

            print(response!)
            guard data != nil else {return}
            do {
                modelPurchase.removeAll()

                let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                print(json)

                let statusRespon = json["status"] as! Bool
                print("Purchase Request - Response status: \(statusRespon)")

                if statusRespon == true {

                    guard let isiData = json["data"] as? [[String: Any]] else {
                        print("Purchase Request - data is empty")
                        return
                    }

                    for dataIsi in isiData {

                        guard let listData = dataIsi["list_data"] as? [[String: Any]] else {
                            print("Purchase Request - list data purchase request is empty")
                            return
                        }

                        for dataList in listData {
                            if ((dataList["year"] as? NSNull) != nil) {
                                self.purYear = "-"
                            }else{
                                self.purYear = dataList["year"] as! String
                            }

                            if ((dataList["tipe"] as? NSNull) != nil) {
                                self.purType = "-"
                            }else{
                                self.purType = dataList["tipe"] as! String
                            }


                            // get flow array
                            guard let flowList = dataList["flow"] as? [[String: Any]] else {
                                print("Get flow PR is empty")
                                return
                            }

                            listFlowStatus.removeAll()
                            listFlagPosition.removeAll()

                            for listFlow in flowList {
                                self.flowStatus = listFlow["flow_status"] as! String
                                self.flagPosition = listFlow["flag_position"] as! String

                                print("=== Flow \(self.flowId) - \(self.flagPosition) ===")

                                listFlowStatus.append(self.flowStatus)
                                listFlagPosition.append(self.flagPosition)

                            }

                            modelPurchase.append(ModelPurchaseRequest(year: self.purYear, type: self.purType, listFlowSatus: listFlowStatus, listFlowPosition: listFlagPosition))
                        }

                    }

                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }

                }else{
                    print("Get list purchase request response status false")
                }

            }catch{
                print(error.localizedDescription)
            }

        }.resume()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return modelPurchase.count
    }

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

        cell.collectionView.reloadData()

        return cell
    }

}

CollectionViewCell.swift类

import UIKit

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var view: UIView!

}

TableViewCell.swift类

import UIKit

class TableViewCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()

        collectionView.dataSource = self as UICollectionViewDataSource
        collectionView.delegate = self as UICollectionViewDelegate

        collectionView.reloadData()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modelPurchase[section].listFlowStatus.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

        let positionNow = modelPurchase[indexPath.section].listFlowPosition[indexPath.row]

        if positionNow == "Green" {
            cell.view.backgroundColor = UIColor.green
        }else if positionNow == "Orange" {
            cell.view.backgroundColor = UIColor.orange
        }else{
            cell.view.backgroundColor = UIColor.red
        }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(modelPurchase[indexPath.section].listFlowPosition[indexPath.row])
    }
}

此处JSON:

{
"status": true,
"message": "Data Show Success",
"data": [
  {
    "list_data": [
        {
          "rowsnum": "1",
          "year": "2018",
          "tipe": "PROGRAM",
          "flow": [
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Red"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Orange"
            }
          ]
        },
        {
          "rowsnum": "2",
          "year": "2018",
          "tipe": "PROJECT",
          "flow": [
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Red"
            },
            {
              "flow_status": "1",
              "flag_position": "Red"
            },
            {
              "flow_status": "1",
              "flag_position": "Orange"
            }
          ]
        },
        {
          "rowsnum": "3",
          "year": "2018",
          "tipe": "PROGRAM",
          "flow": [
            {
              "flow_status": "1",
              "flag_position": "Red"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Orange"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            },
            {
              "flow_status": "1",
              "flag_position": "Green"
            }
          ]
        }
      ]
  }
]
}

1 个答案:

答案 0 :(得分:1)

请按以下方式更改代码:

步骤1: 在tableView cellForRowAt方法中,请输入:

cell.collectionView.tag = indexPath.row

第2步: 然后在collectionView numberOfItemsInSection方法中输入:

return modelPurchase[collectionView.tag].listFlowStatus.count

步骤3: 在collectionView cellForItemAt方法中写:

let positionNow = modelPurchase[collectionView.tag].listFlowPosition[indexPath.row]

相应地更改代码。可能对您有所帮助。谢谢