【发布时间】:2015-03-31 00:41:27
【问题描述】:
我有一个带有自定义单元格的 UICollectionView。每个自定义单元格都包含一个 UITableView。我遇到的问题是表视图返回错误的行数。当我从 CustomCell.swift 在numberOfRowsInSection 中打印 data.count 时,计数不正确。但是,当我从 CustomCell.swift 中的 cellForRowAtIndexPath 或 ViewController.swift 中的 cellForItemAtIndexPath 打印 data[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 行和第一个单元格中的数据。
【问题讨论】:
-
谢谢@Rob。对不起,如果它令人困惑。我在上面添加了更多上下文。当我说 ViewController.swift 正在打印正确的值时,我的意思是我传递给 CustomCell 的值是正确的。