msoto
msoto

Reputation: 41

How do I get the correct indexPath.section from a button in a collection view, which is inside a table view?

I'm setting up a button inside the FooterView, which belongs to a collectionView, and this is inside a TableView. How do I get the indexPath.section from this button?

This is for a new segmented control's tab. In the past, I've tried to assign the indexPath.section to an int variable, and even assign a number to a constant, used prepareForReuse method in the cells to update the cell, but it always gives me the wrong index. It changes while I scroll.

var currentlyActiveCellIndexPath: Int?

extension LibraryViewController {
    func viewTapped(button: UIButton) {

        let tapgesture = UITapGestureRecognizer.init(target: self, action: #selector(goToViewAllArticles))
        button.addGestureRecognizer(tapgesture)

        let tapgesture1 = UITapGestureRecognizer.init(target: self, action: #selector(goToViewAllPodcasts))
        button.addGestureRecognizer(tapgesture1)



        tapgesture.numberOfTapsRequired = 1

        button.isUserInteractionEnabled = true



    }
    @objc func goToViewAllArticles(sender: UITapGestureRecognizer) {
        return self.performSegue(withIdentifier: "showBrowseFromButton", sender: currentlyActiveCellIndexPath)
    }

    @objc func goToViewAllPodcasts(sender: UITapGestureRecognizer) {
        return self.performSegue(withIdentifier: "showBrowseFromButton", sender: currentlyActiveCellIndexPath)
    }


  func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {


        currentlyActiveCellIndexPath = indexPath.section

I have expected the indexPath.section to remain the same, but once I scroll, it changes and I can't get the right indexPath.section.

Upvotes: -1

Views: 323

Answers (1)

Rishabh Shukla
Rishabh Shukla

Reputation: 501

set tag of your button as indexPath

in cellForRowAt(:)

YourBtn.tag = indexPath.row

now u can get exact same indexPath when u tap on that button if still not working leave a comment !

Upvotes: 0

Related Questions