iOS 14 UIMenu replacingChildren does not work

864 views Asked by At

I want to add an UIMenu with conditional menu children to a UIButton's menu on iOS14, but the replacingChildren does not work.

self.button.menu = UIMenu( options: .displayInline, children:[
       UIAction(title:"Action 1"){_ in},
       UIAction(title:"Action 2"){_ in}
   ])
//Try to update menu's children but it does not work

self.button.menu = self.button.menu?.replacingChildren([ 
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
 ])

The menu does not change. I need to create a completely new instance of UIMenu with new children and assign it to self.button.menu. How to use replacingChildren or any mistake?

1

There are 1 answers

0
lucasl On

I stumbled upon this as well. For some reason using replacingChildren resulted in the unaltered children array on iOS 14. For iOS 15 the behavior is as expected.

However, I was able to go around this by just setting a newly instantiated UIMenu instead.

In your case by calling:

self.button.menu = UIMenu(options: .displayInline, children:[
    UIAction(title:"Action 3"){_ in},
    UIAction(title:"Action 4"){_ in}
])

Since this isn't the greatest solution and (for me) it was only needed for iOS 14 you might want to only use this when needed:

if #available(iOS 15.0, *) {
   self.button.menu = self.button.menu?.replacingChildren([ 
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
} else {
   self.button.menu = UIMenu(options: .displayInline, children:[
      UIAction(title:"Action 3"){_ in},
      UIAction(title:"Action 4"){_ in}
   ])
}

I hope this might help whoever needs it.