首页 > 解决方案 > 将collectionView连接到tableView

问题描述

CollectionView的主故事板上有 5 个单元格,单击这些单元格后,CollectionView故事板上移动到另一个视图上,该视图是TableView表格视图单元格内部,我想放置我的数据,这是一个数组。我的代码工作正常,直到将数据放入TableView

任何解决方案都会得到应用<3

extension ViewController: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cars.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as? CollectionViewCell
        cell?.setup(with: cars[indexPath.row])
        return cell!
    }
}
extension ViewController:UICollectionViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cars.count
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = storyboard?.instantiateViewController(identifier: "TableViewController") as? TableViewController
        self.navigationController?.pushViewController(vc!, animated: true)
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
        cell.configure(with: cars[indexPath.row])
        return cell
    }
}

数据Cars

struct Cars {
    let carName:String
    let carModel:[String]
}
let cars:[Cars] = [
    Cars(carName: "Mercedes", carModel: ["S Class","A Class", "B Class"]),
    Cars(carName: "BMW", carModel: ["X5","X6","X7"]),
    Cars(carName: "Ford", carModel: ["Fuison","Focus","Mustang"]),
    Cars(carName: "Toyota", carModel: ["Camry", "Corolla"]),
    Cars(carName: "Hyundai", carModel: ["Elantra"])
]

表格视图单元格代码:

class TableViewCell: UITableViewCell {
    @IBOutlet weak var lbl: UILabel!
    func configure(with cars:Cars){
        lbl.text = cars.carName
    }
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

标签: swift

解决方案


推荐阅读