How to modify UIMenu for UIBarButtonItem and UIButton

社会主义新天地 提交于 2020-12-06 04:35:05

问题


iOS 14 adds the ability to display menus upon tapping or long pressing a UIBarButtonItem or UIButton, like so:

let menu = UIMenu(children: [UIAction(title: "Action", image: nil) { action in
    //do something
}])
button.menu = menu
barButtonItem = UIBarButtonItem(title: "Show Menu", image: nil, primaryAction: nil, menu: menu)

This most often replaces action sheets (UIAlertController with actionSheet style). It's really common to have a dynamic action sheet where actions are only included or may be disabled based on some state at the time the user taps the button. But with this API, the menu is created at the time the button is created. How can you modify the menu prior to it being presented or otherwise make it dynamic to ensure the appropriate actions are available and in the proper state when it will appear?


回答1:


One solution I found is to store a reference to your bar button item or button and recreate the menu each time any state changes that affects the available actions in the menu. menu is settable property so it can be changed any time after the button is created. You can also get the current menu and replace its children like so: button.menu = button.menu?.replacingChildren([])

For scenarios where you are not informed when the state changes, you really need to be able to update the menu right before it appears. For UIButton, you could change the menu when the user touches down on the button via target/action like so: button.addTarget(self, action: #selector(buttonTouchedDown(_:)), for: .touchDown). I confirmed this works with iOS 14 beta at least at this time, but only if showsMenuAsPrimaryAction is false so they have to long press to open the menu. I haven't found a solution for UIBarButtonItem, but you could use a UIButton as a custom view for the UIBarButtonItem.

These don't feel like great solutions, will update if I find something better.



来源:https://stackoverflow.com/questions/62970548/how-to-modify-uimenu-for-uibarbuttonitem-and-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!