UIMenuController with custom item not working with UICollectionview

前端 未结 6 1054
长情又很酷
长情又很酷 2021-01-13 02:15

I have added custom menu controller when long press on UICollectionViewCell

    [self becomeFirstResponder];
    UIMenuItem *menuItem = [[UIMenuItem alloc] i         


        
6条回答
  •  梦谈多话
    2021-01-13 02:49

    Swift 3 Solution:

    Simply do all stuff inside UICollectionView class and assign this class to UICollectionView object.

    import UIKit
    
    class MyAppCollectionView: UICollectionView {
    
        required public init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            addLongPressGesture()
        }
    
        func addLongPressGesture() {
            let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(MyAppCollectionView.longPressed(_:)))
            longPressGesture.minimumPressDuration = 0.5
            self.addGestureRecognizer(longPressGesture)
        }
    
        func longPressed(_ gesture: UILongPressGestureRecognizer) {
    
            let point = gesture.location(in: self)
            let indexPath = self.indexPathForItem(at: point)
    
            if indexPath != nil {
    
                MyAppViewController.cellIndex = indexPath!.row
                let editMenu = UIMenuController.shared
                becomeFirstResponder()
                let custom1Item = UIMenuItem(title: "Custom1", action: #selector(MyAppViewController.custome1Method))
                let custom2Item = UIMenuItem(title: "Custom2", action: #selector(MyAppViewController.custome2Method))
                editMenu.menuItems = [custom1Item, custom2Item]
                editMenu.setTargetRect(CGRect(x: point.x, y: point.y, width: 20, height: 20), in: self)
                editMenu.setMenuVisible(true, animated: true)
            }
    
        }
    
        override var canBecomeFirstResponder: Bool {
    
            return true
        }
    }
    
    class MyAppViewController: UIViewController {
    
         override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
                // You need to only return true for the actions you want, otherwise you get the whole range of
                //  iOS actions. You can see this by just removing the if statement here.
    
                //For folder edit
                if action == #selector(MyAppViewController.custome1Method) {
                    return true
                }
    
                if action == #selector(MyAppViewController.custome2Method) {
                    return true
                }
    
                return false
            }
    }
    

提交回复
热议问题