1

Hy guys, i create multiple UIMenuItem with the same selector:

["first", "second", "third"].forEach({ (menu) in
    let b = UIMenuItem(title: menu, action: #selector(target.tap(sender:)))
})

@objc public func click(sender: UIMenuItem){
    print("click: \(sender)")
}

But the sender object I receive is not of type: UIMenuItem, so If I use:

@objc public func click(sender: UIMenuItem){
    print("click: \(sender.title)")
}

to know which button did tap, I obtain error, if I use:

@objc public func click(sender: UIMenuController){
    print("click: \(sender.menuItems)")
}

i see the right number of items, how can I access the tapped one without using one selector for each one?

Thanks!

Krunal
  • 77,632
  • 48
  • 245
  • 261
Luca Becchetti
  • 1,210
  • 1
  • 12
  • 28

2 Answers2

0

Unfortunately, there is no any option (delegate, function/method or variable/property) providing information about selected menu item.

I did face same issue and couldn't find anything. At last I implemented a manual practice, like this:

var menuItems =  [UIMenuItem]()

menuItems.append(UIMenuItem(title: "First", action: #selector(self.firstMenuClick(_:))))

menuItems.append(UIMenuItem(title: "Second", action: #selector(self.secondMenuClick(_:))))

menuItems.append(UIMenuItem(title: "Third", action: #selector(self.thirdMenuClick(_:))))

UIMenuController.shared.menuItems = menuItems


@objc public func firstMenuClick(sender: UIMenuController){
    print("firstMenuClick")
}

@objc public func secondMenuClick(sender: UIMenuController){
    print("secondMenuClick")
}


@objc public func thirdMenuClick(sender: UIMenuController){
    print("thirdMenuClick")
}

I'm also looking for better answer, than I used but you can try this to solve your problem, if you can't find any better way.

Krunal
  • 77,632
  • 48
  • 245
  • 261
0

You could implement UIMenu, with UIAction's. UIAction supports a handler instead, them differentiate between either the identifier, or the name. Here's an example:

let menuAction = { (action: UIAction) in

    let identifier = action.identifier.rawValue
    let title = action.title

    // do something with identifier / title here
}

var actions: [UIAction] = [
    UIAction(
        title: "Please select",
        identifier: UIAction.Identifier("myStringValue"),
        handler: menuAction
    )
]

mybutton.menu = UIMenu(children: actions)
mybutton.showsMenuAsPrimaryAction = true
mybutton.changesSelectionAsPrimaryAction = true
Declan Land
  • 639
  • 2
  • 11
  • 27