我有一个带有自定义单元格的 UICollectionView。每个自定义单元格都包含一个 UITableView。我遇到的问题是 TableView 返回错误的行数。当我从 CustomCell.swift 在 numberOfRowsInSection
中打印 data.count 时,计数不正确。但是,当我从 CustomCell.swift 中的 cellForRowAtIndexPath
或 ViewController.swift 中的 cellForItemAtIndexPath
打印数据[indexPath.row].count 时,计数是正确的。我做错了什么?
ViewController.swift
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var collectionView:UICollectionView!
var layout = UICollectionViewFlowLayout()
let kCustomCellIdentifier = "CustomCell"
let data = [[5, 4, 3, 2],[0, 1, 2, 3],[9, 8, 7, 6, 5]]
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kCellIdentifier, forIndexPath: indexPath) as! CustomCell
//data[indexPath.row].count returns the correct value
cell.numbers = data[indexPath.row]
return cell
}
}
CustomCell.swift
class CustomCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate {
let kCustomTableCell = "CustomTableCell"
var numbers:[Int]!
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView(frame: frame, style: .Plain)
tableView.registerClass(CustomTableCell.self, forCellReuseIdentifier: kCustomTableCell)
tableView.delegate = self
tableView.dataSource = self
contentView.addSubview(tableView)
}
override func prepareForReuse() {
super.prepareForReuse()
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//numbers.count returns the wrong value
return numbers.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//numbers.count returns the correct value
let cell = tableView.dequeueReusableCellWithIdentifier(kCustomCell) as! CustomTableCell
return cell
}
数据
data = [[5, 4, 3, 2],[0, 1, 2, 3],[9, 8, 7, 6, 5]]
我希望第一个单元格有 4 行,第二个单元格我希望有 4 行,第三个单元格我希望有 5 行。相反,第三个单元格返回 4 行和第一个单元格的数据。
最佳答案
不确定这是否是一个好的解决方案,但它确实有效。
var numbers:[Int]! {
didSet{
tableView.reloadData()
}
}
关于iOS swift : TableView numberOfRowsInSection returning wrong count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29358714/