2017-04-05 15 views
3

我想添加一個TableView裏面的UICollectionViewCell,所以我想從TableView自己管理該單元格。 所以更清楚的是,如果indexPath.row是2,那麼我想調用我的tableView單元格里面的collectionview indexPath.row。以特定的UICollectionViewCell編程的TableView?

請檢查圖片,我用紅色做了我想做的事情。 我使用UICollectionViewController和UICollectionViewControllerFlowLayout以編程方式創建了所有內容。

+0

此截圖中的UICollectionView在哪裏? – luk2302

+0

屏幕是所有UICollectionView,即使它看起來不像CollectionView。 –

回答

2

您可以創建爲indexpath定製UICollectionView細胞。並在單元格xib中添加一個tableview。

在自定義單元類中實現tableview的委託方法。

class CustomCollectionViewCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate 
    { 
    @IBOutlet var tableView: UITableView! 

    override func layoutSubviews() 
    { 
     super.layoutSubviews() 
     tableView.delegate = self 
     tableView.dataSource = self 
    } 
    } 
2

對於那些誰需要它,我找到了解決辦法:

class CustomizedCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate { 

    var tableView = UITableView() 
    let cellIdentifier: String = "tableCell" 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     tableView.delegate = self 
     tableView.dataSource = self 

     tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) 
} 
func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 4 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: cellIdentifier) 

    cell.textLabel?.text = "1 CUP" 
    cell.detailTextLabel?.text = "Whole" 

    return cell 
} 

}

然後在viewDidLoad方法在的CollectionView我這樣做:

collectionView?.register(CustomizedCell.self, forCellWithReuseIdentifier: "cell") 

在這之後我在UICollectionView的cellForRowAt indexPath方法中調用了這樣的方法:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomizedCell 

    return cell 
} 
+0

我沒有看到何時將'UITableview'添加到收集單元? – skymook

相關問題