【问题标题】:How do I get the correct indexPath.section from a button in a collection view, which is inside a table view?如何从表视图内的集合视图中的按钮获取正确的 indexPath.section?
【发布时间】:2020-01-02 15:59:52
【问题描述】:

我在FooterView里面设置了一个按钮,它属于一个collectionView,它在一个TableView里面。如何从此按钮获取 indexPath.section?

这是一个新的分段控件的选项卡。过去,我尝试将 indexPath.section 分配给 int 变量,甚至将数字分配给常量,在单元格中使用 prepareForReuse 方法来更新单元格,但它总是给我错误的索引。当我滚动时它会改变。

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

我希望 indexPath.section 保持不变,但是一旦滚动,它就会改变,我无法获得正确的 indexPath.section。

【问题讨论】:

    标签: swift uitableview uicollectionviewcell prepareforreuse


    【解决方案1】:

    将按钮的标签设置为 indexPath

    在 cellForRowAt(:) 中

    YourBtn.tag = indexPath.row
    

    现在,当您点击该按钮时,如果仍然无法使用,您可以获得完全相同的 indexPath 并发表评论!

    【讨论】:

    • 按钮连接到一个Footerreusableview:UIReusableCollectionView。在 cellForRow 中,每一行都连接到一个 xib 文件。我通过 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 如果我尝试通过 collectionView 的 cellForRow 访问,通过创建 var footerView = ReusableFooterView() 并访问 footerView .myButton.tag = indexPath.row 它崩溃了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多