2015-03-31 26 views
0

我有一個自定義單元格的UICollectionView。每個自定義單元格都包含一個UITableView。我遇到的問題是表視圖返回錯誤的行數。當我從CustomCell.swift打印numberOfRowsInSection中的data.count時,計數不正確。但是,當我打印數據[indexPath.row] .count從cellForRowAtIndexPath CustomCell.swift或cellForItemAtIndexPath在ViewController.swift計數是正確的。我究竟做錯了什麼?iOS的Swift:TableView numberOfRowsInSection返回錯誤的計數

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]] 

第一小區予實驗值ect有4行,第二個單元我期望有4行,第三個單元我期望有5行。相反,第三個單元格返回4行,並從第一個單元格返回數據。

+1

Thanks @Rob。對不起,如果它很混亂。我在上面添加了更多內容。當我說ViewController.swift正在打印正確的值時,我的意思是我傳入CustomCell的值是正確的。 – colindunn 2015-03-31 01:00:29

回答

1

不知道這是否是一個好的解決方案,但它的工作原理。

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

哇這是我學到的最好的新東西didSet {} – 2017-07-25 11:57:27