Search code examples
iosswiftuitableviewuicollectionviewindexpath

How to get a image's indexpath in CollectionView in TableView?


In my program, each row of TableView has a Collection, each CollectionView has several Images. I have set Tag and UITapGestureRecognizer for the image in the collectionView(_:, cellForItemAt:) method, but Tag can only represent the position of the image in the CollectionView. How do I know the position of the clicked image in the Table and pass the row of TableView and the row of Collection to UITapGestureRecognizer(target:, action: #selector()) method?


Solution

  • You can do something like this:

    func imageTapped(gesture: UITapGestureRecognizer) {
        let location: CGPoint = gesture.location(in: tableView)
        let ipath: IndexPath? = tableView.indexPathForRow(at: location)
        let cellindex: UITableViewCell? = tableView.cellForRow(at: ipath ?? 
     IndexPath(row: 0, section: 0))
     }