How to show a custom UIMenuItem for a UITableViewCell?

后端 未结 3 632
名媛妹妹
名媛妹妹 2020-11-29 01:56

I want the UIMenuController that pops up when I long-press a UITableViewCell to show custom UIMenuItems.

I set up the custom item in viewDidLoad

UIMe         


        
3条回答
  •  孤街浪徒
    2020-11-29 02:43

    To implement copy and a custom action for UITableViewCell:

    Once in your application, register the custom action:

    struct Token { static var token: dispatch_once_t = 0 }
    dispatch_once(&Token.token) {
        let customMenuItem = UIMenuItem(title: "Custom", action: #selector(MyCell.customMenuItemTapped(_:))
        UIMenuController.sharedMenuController().menuItems = [customMenuItem]
        UIMenuController.sharedMenuController().update()
    }
    

    In your UITableViewCell subclass, implement the custom method:

    func customMenuItemTapped(sender: UIMenuController) {
        // implement custom action here
    }
    

    In your UITableViewDelegate, implement the following methods:

    override func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    
    override func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return action == #selector(NSObject.copy(_:)) || action == #selector(MyCell.customMenuItemTapped(_:))
    }
    
    override func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
        switch action {
        case #selector(NSObject.copy(_:)):
            // implement copy here
        default:
            assertionFailure()
        }
    }
    

    Notes:

    • This uses the new Swift 3 #selectors.
    • See this answer for info on how to implement copy.

提交回复
热议问题