如何获取在tableview单元格内的collectionview单元格的按钮单击上的索引

Xco*_*der 4 uitableview ios uicollectionview swift

我在tableView单元格中嵌入了collectionView。CollectionView有多个项目,其中包含按钮。在UITableViewCell中设置了集合视图数据源和委托。为此,我必须基于该按钮选择执行一些操作,我需要知道collectionView单元格indexPath和tableView单元格indexPath。但无法弄清楚如何实现这一目标。尝试使用委托,但不知道如何在委托方法中获取collectionView引用。

CollectionView单元格

protocol SelectedItemCellDelegate:class {
func deleteButtonDidTapped(_ cell: SelectedItemCell)
}
 class SelectedItemCell: UICollectionViewCell {
class var identifier: String{
    return String(describing: self)
}
class var nib: UINib{
    return UINib(nibName: identifier, bundle: nil)
}
@IBOutlet weak var deleteButton: UIButton!
weak var delegate: SelectedItemCellDelegate?
override func awakeFromNib() {
    super.awakeFromNib()
}

@IBAction func deleteAction(_ sender: Any) {
    delegate?.deleteButtonDidTapped(self)
}
}
Run Code Online (Sandbox Code Playgroud)

ViewController

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:SelectedItemCell.identifier, for: indexPath) as! SelectedItemCell
cell.delegate = self                        
return cell
  }

 extension PrescriptionVC: SelectedItemCellDelegate
{   
    func deleteButtonDidTapped(_ cell: SelectedItemCell) 
    {
      // Need tableview indexPath as well SelectedItemCell indexPath.
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要两个代表

protocol selectCollectionCellDelegate {

 func selectCell(cell : UICollectionViewCell )     

}

protocol selectTableCellDelegate {

 func selectTableCell(cell : UITableViewCell , indexPath : IndexPath )

}



class YourCollectionViewCell : UICollectionViewCell {

  var tvcDelegate : selectCollectionCellDelegate


@IBAction func deleteAction(_ sender: Any) {
    tvcDelegate.selectCell(cell : self)
 }

}



class YourTableViewCell : UITableViewCell , selectCollectionCellDelegate {

  var vcDelegate : selectTableCellDelegate

 func selectCell(cell : UICollectionViewCell ){

     let indexPath : IndexPath = collectionView.indexPath(for: cell)!

     delegate.selectTableCell(cell : self , indexPath : indexPath  )
  } 

}






class YourviewController : UIViewController , selectTableCellDelegate{


 func selectTableCell(cell : UITableViewCell , indexPath : IndexPath){
   //indexPatn is IndexPath of collectionViewCell
   let tableCellindexPath : IndexPath = tableView.indexPath(for: self)!
  } 

}
Run Code Online (Sandbox Code Playgroud)