0
votes

I am trying to display a custom action using UIMenuController on a UICollectionViewController subclass, and even though the cut, copy and paste actions appears as expected, for some reason my custom action doesn't.

I followed a lot of references from the web but none of them makes it work, here the code:

class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    fileprivate var items = [MyClass]()

    // MARK: - UICollectionViewDataSource
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath)
        /* update cell properties */
        return cell
    }

    // MARK: - UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: itemSize, height: itemSize)
    }

    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
        /* Do Something */
    }

    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    public func menuAction(_ sender: UIMenuItem) {
        /* Action method*/
    }
}

Tried to add the menu item as follows:

        let menuItem = UIMenuItem(title: SFLocalization.localizedString("Common-remove"), action: #selector(CollectionViewController.menuAction(_:)))
        let menuController = UIMenuController.shared
//        menuController.menuItems?.append(menuItem)
        menuController.menuItems = [menuItem]

on both viewDidLoad and collectionView(_ collectionView:, shouldShowMenuForItemAt) -> Bool

Any ideas?

1
Running into a similar issue; did you ever have any luck finding a solution?John Stewart

1 Answers

0
votes

Omer - check out this link: http://dev.glide.me/2013/05/custom-item-in-uimenucontroller-of.html

Basically, moving these methods:

  • (BOOL)canPerformAction:(SEL)action withSender:(id)sender {

  • (BOOL)canBecomeFirstResponder {

... to the CollectionView cell subclass works. You then have to pass this selector back up to the cell delegate.

With this, I was able to get my custom menu to appear!