Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift- Set Visible menucontroller

Tags:

xcode

swift

I'm trying to display a UimenuController but I can not view it. how can I do?

let MenuController: UIMenuController = UIMenuController.sharedMenuController()
 MenuController.menuVisible = true
 MenuController.arrowDirection = UIMenuControllerArrowDirection.Down
 MenuController.setTargetRect(CGRectMake(100, 80, 50, 50), inView: self.view)
 let MenuItem_1: UIMenuItem = UIMenuItem(title: "Menu", action: "delete:")
 let MenuItems: NSArray = [delete]
 MenuController.menuItems = MenuItems
like image 976
Massimo Negro Avatar asked Nov 30 '22 01:11

Massimo Negro


2 Answers

In order to actually have the menu to display you need to do the following:

  1. Call becomeFirstResponder() before you get your sharedMenuController
  2. Call menu.setMenuVisible(true, animated: true) at the end
  3. Override the canBecomeFirstResponder function
  4. Override the canPerformAction function
  5. Write the function for the selector

Here is an example

func someFunc() {
    becomeFirstResponder()
    var menu = UIMenuController.sharedMenuController()
    var deleteItem = UIMenuItem(title: "Delete me", action: Selector("deleteLine"))
    menu.menuItems = [deleteItem]
    menu.setTargetRect(CGRectMake(100, 80, 50, 50), inView: self)
    menu.setMenuVisible(true, animated: true)
}

func deleteLine() {
    //Do something here
}

override func canBecomeFirstResponder() -> Bool {
    return true
}

override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> 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.
    if action == Selector("deleteLine") {
        return true
    }
    return false
}
like image 69
Aleksandr Movsesyan Avatar answered Dec 16 '22 22:12

Aleksandr Movsesyan


Swift 3 version code:

func someFunc() {
    becomeFirstResponder()
    var menu = UIMenuController.shared
    var deleteItem = UIMenuItem(title: "Delete me", action: #selector(ViewController.deleteLine))
    menu.menuItems = [deleteItem]
    menu.setTargetRect(CGRect(x: 0.0, y: 0.0, width: 20, height: 20), in: self)
    menu.setMenuVisible(true, animated: true)
}

func deleteLine() {
    //Do something here
}

override var canBecomeFirstResponder: Bool {

        return true
    }

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.
        if action == #selector(ViewController.deleteLine) {
            return true
        }

        return false
    }
like image 33
mriaz0011 Avatar answered Dec 16 '22 22:12

mriaz0011