繁体   English   中英

collectionView单元格中的按钮选择器

[英]selector for button inside collectionView cell

这让我疯了,我已经读了好几个小时并试了一切,不能让这个按钮选择器工作。 这应该不难。

在CellForItemAt内部我设置了按钮标签并尝试调用按钮。

cell.deleteCellButton.tag = indexPath.item
cell.deleteCellButton.addTarget(self, action: #selector(deleteCellButtonTapped(sender:)), for: UIControlEvents.touchUpInside)

我试过(_ :),“deleteCellButtonTapped:”,以及任何其他数量的括号组合,我仍然得到无法识别的选择器。 我不知道为什么autocomplete建议(发送者:)我以前从未见过这个。

然后我的按钮功能:

func deleteCellButtonTapped(sender: UIButton!) {
    self.packArray.remove(at: sender.tag)
        print(packArray.count)
    self.outerCollectionView.deleteItems(at: [IndexPath(item: sender.tag, section: 0)])

    self.outerCollectionView.reloadData()
    self.outerCollectionView.layoutIfNeeded()
}

假设您正在使用Swift 3,并且func deleteCellButtonTapped(sender: UIButton!)位于同一个类中:

addTarget(self, action: #selector(deleteCellButtonTapped(sender:)), for: .touchUpInside)

工作正常。

从它的类中引用选择器方法对我有用。

你可以做的是访问选择器方法前缀为它的类名

我假设你的类名是MyClassViewController 你的代码看起来像:

class MyClassViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    .... // Other implementation methods

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

        ....// create cell object and dequeue

        cell.deleteCellButton.addTarget(self, action: #selector(MyClassViewController.deleteCellButtonTapped(_:)), for: .touchUpInside)
        return cell
    }

    func deleteCellButtonTapped(_ sender: Any) {
         // your method implementation
          print("Selector method called")
    }
}

希望这很好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM