0

我有一个 UICollectionView 嵌套在表格视图单元格内。如何获取collectionview单元格水平行的索引路径?我试着用

        let index = cell.tag

        print(index as Any) 

打印选择了哪个索引,但不知道无论我选择什么单元格,它都会打印零值。抱歉,我对收藏视图没有经验。任何帮助深表感谢。谢谢。

4

2 回答 2

0

您应该设计一个处理嵌套 UIElement 交互的协议。它让你的头脑更清晰,分配更好的地址

class ViewwithTable:UIViewController,UITableViewDataSource,collectionCell_delegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "temp", for: indexPath) as! NestedViewwithCollection
        cell.delegate = self
        return cell
    }

    func didPressed(indexPath: IndexPath) {
        //the pressed index!
    }
}

class NestedViewwithCollection:UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate{
    var delegate:collectionCell_delegate?

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

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let del = delegate{
            del.didPressed(indexPath: indexPath)
        }
    }

}

protocol collectionCell_delegate {
    func didPressed(indexPath:IndexPath)
}
于 2017-10-03T04:10:16.100 回答
0

将此代码用于 tableView

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return model.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    return cell
}

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) 
{
    guard let tableViewCell = cell as? TableViewCell else { return }
    tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
}

集合视图

extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource 
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return model[collectionView.tag].count
}

func collectionView(collectionView: UICollectionView, 
    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", 
        forIndexPath: indexPath)

    cell.backgroundColor = model[collectionView.tag][indexPath.item]

    return cell
}
于 2017-10-03T04:54:06.183 回答