【问题标题】:iOS Swift: TableView numberOfRowsInSection returning wrong countiOS Swift:TableView numberOfRowsInSection 返回错误计数
【发布时间】: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 的值是正确的。

标签: ios swift uikit


【解决方案1】:

不确定这是否是一个好的解决方案,但它确实有效。

var numbers:[Int]! {
    didSet{
        tableView.reloadData()
    }
}

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    相关资源
    最近更新 更多