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
In order to actually have the menu to display you need to do the following:
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
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With