Tip for working with UIMenu declares and MobileToolbarButton

iOSKit has some declares for attaching iOS 14’s UIMenus to buttons, but tonight I needed to attach them to a MobileToolbarButton, which requires some extra work. iOSKit’s example code is almost usable out of the box, but you’ll need to not call this declare because MobileToolbarButton (implemented via UIBarButtonItem) doesn’t have this method:

Declare sub showsMenuAsPrimaryAction lib UIKitLib selector "setShowsMenuAsPrimaryAction:" (obj as ptr, value as boolean)
showsMenuAsPrimaryAction(me.Handle, true)

The menus will now work on your MobileToolbarButton, but will only work with a long press. If you tap the button, it will call the ToolbarButtonPressed event of the parent MobileScreen. So you need to remove the MobileToolbarButton’s (UIBarButtonItem) action handler. I struggled with this for a while but eventually discovered that this needs to be done after the Opening event for the MobileScreen. I stick this code in the Resized handler:

// Remove the MobileToolbarButton action; only setAction:nil works. setPrimaryAction:nil won't work
Declare Sub setAction Lib UIKitLib Selector "setAction:" (obj As ptr, action As ptr)
setAction(B_Menu.Handle, Nil)

Now, you’ll have a custom menu in your MobileToolbarButton that you can show via a single tap:

5 Likes

Thanks very much John for sharing this. It’s actually not working for me, but expect I’m doing something wrong.

In the Opening even of the Screen, I have

Declare sub showsMenuAsPrimaryAction lib UIKitLib selector "setShowsMenuAsPrimaryAction:" (obj as ptr, value as boolean)
showsMenuAsPrimaryAction(me.Handle, true)

Followed by

Declare Sub setAction Lib UIKitLib Selector "setAction:" (obj As ptr, action As ptr)
setAction(B_Menu.Handle, Nil)

(I named the OBMobileToolbarButton as ‘B_Menu’)

It crashes as it attempts showsMenuAsPrimaryAction

Any ideas?

Thanks for your time.

1 Like

As John described, the call to setAction needs to happen after the Opening event.

You can place the code in the Resized or Activated event :wink:

Edit:

Can only be called on a UIButton

2 Likes