首页 > 解决方案 > TableView Cell 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"
            }
          ]
        }
      ]
  }
]
}

标签: tableviewswift4collectionview

解决方案


请更改代码如下:

第 1 步:在 tableViewcellForRowAt方法中请写:

cell.collectionView.tag = indexPath.row

Step2:然后在collectionViewnumberOfItemsInSection方法中请写:

return modelPurchase[collectionView.tag].listFlowStatus.count

第 3 步:在 collectionViewcellForItemAt方法中写入:

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

相应地更改代码。它可能对你有帮助。谢谢


推荐阅读