如何为UIBarButtonItem和UIButton修改UIMenu [英] How to modify UIMenu for UIBarButtonItem and UIButton

查看:395
本文介绍了如何为UIBarButtonItem和UIButton修改UIMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS 14增加了在点击或长按UIBarButtonItem或UIButton时显示菜单的功能,例如:

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)

这通常替换操作单(UIAlertController替换为actionSheet样式).动态操作表通常很常见,其中仅包含动作,也可以根据用户点击按钮时的某些状态来禁用动作.但是,使用此API,可以在创建按钮时创建菜单.如何显示菜单之前如何对其进行修改,或者如何使其动态化,以确保出现适当的操作并使其处于适当的状态?

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?

推荐答案

我发现的一个解决方案是,存储对条形按钮项或按钮的引用,并在每次影响菜单中可用操作的任何状态更改时重新创建菜单. . menu是可设置的属性,因此可以在创建按钮后随时对其进行更改.您还可以获取当前菜单并替换其子菜单,如下所示:button.menu = button.menu?.replacingChildren([])

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([])

对于状态何时发生变化不通知您的情况,您确实需要能够在菜单出现之前立即对其进行更新.对于UIButton,您可以在用户通过目标/操作按下按钮时更改菜单,如下所示:button.addTarget(self, action: #selector(buttonTouchedDown(_:)), for: .touchDown).我确认了至少在目前至少可以在iOS 14 beta上使用,但是仅当showsMenuAsPrimaryAction为false时,他们才需要长按打开菜单.我还没有找到UIBarButtonItem的解决方案,但是您可以将UIButton用作UIBarButtonItem的自定义视图.

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.

这篇关于如何为UIBarButtonItem和UIButton修改UIMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆