swift - 将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)
}
}
解决方案
推荐阅读
- mysql - 拥有数百万张表的数据库
- python - 视频系统未初始化错误,即使已初始化
- c++ - clang 编译的程序在 std::any_cast 期间抛出 std::bad_any_cast
- java - 使用 servlet 搜索数据库
- php - WordPress:无法删除“ob_end_flush()”中的缓冲区 zlib 输出压缩
- java - 为什么存储在 arrayList 中的每个对象的内容具有相同的值?
- javascript - 我不断收到此错误,这是我使用的代码。错误每个 then() 应该返回一个值或抛出
- bash - 如何使用管道命令创建屏幕
- php - php中通过curl发送数据的问题
- javascript - 如何在创建具有相似结构的新对象时递归迭代 JS 对象?