Swift 中 UIMenu 中子菜单选项的复选标记

Ant*_*ony 5 contextmenu ios swift

我有以下代码,当用户点击uibarbutton导航栏中的 a 时,它会生成上下文菜单:

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .systemGreen
        title = "Hello"
        
        let scribbleAction =  UIAction(title: "Scribble", image: UIImage(systemName: "scribble"), state: .on, handler: { (_) in })
        let textAction =  UIAction(title: "Typing", image: UIImage(systemName: "textformat"), state: .off, handler: { (_) in })
        
        let clockAction = UIAction(title: "Show Clock", image: UIImage(systemName: "clock"), state: .off, handler: { (_) in })
        let calendarAction = UIAction(title: "Date Last Used", image: UIImage(systemName: "calendar"), state: .off, handler: { (_) in })
        
        var showAsActions: [UIAction] {
            return [
                clockAction, calendarAction
            ]
        }
        
        var showAsMenu : UIMenu {
            return UIMenu(title: "Show As", image: UIImage(systemName: "questionmark.circle.fill"), identifier: .none, children: showAsActions)
        }
    
        let menu = UIMenu(title: "",
                          image: nil,
                          identifier: nil,
                          options: [],
                          children: [showAsMenu, scribbleAction, textAction])
                
        let barButtonRight = UIBarButtonItem(title: "Sort", image: UIImage(systemName: "ellipsis.circle.fill"), primaryAction: nil, menu: menu)
        navigationItem.rightBarButtonItems = [barButtonRight]
    }
}
Run Code Online (Sandbox Code Playgroud)

当用户点击导航栏中的按钮时,这一切都会起作用并产生以下结果:

在此输入图像描述

点击第一个菜单项会产生所需的效果:

在此输入图像描述

但有时,我还需要能够用复选标记标记第一个菜单项(这是一个子菜单项)。我不知道如何做到这一点,并且在 Stackoverflow 以及 Apple 开发者论坛等上进行了搜索,但无法解决。任何建议将不胜感激。

小智 0

如果您只需要担心 iOS 15 及更高版本,请尝试传递UIMenu.Options.singleSelectionUIMenu驱动该showAsMenu属性的 init。

var showAsMenu: UIMenu {
    return UIMenu(title: "Show As", 
                  image: UIImage(systemName: "questionmark.circle.fill"), 
                  identifier: .none,
                  options: .singleSelection,
                  children: showAsActions)
}
Run Code Online (Sandbox Code Playgroud)

根据您希望主菜单的行为方式,您可以将该选项传递到 init 中menu,因为该选项会考虑它传递到的菜单及其所有子菜单。

如果您支持 iOS 14,不幸的是,您可能不得不重新创建整个菜单,根据需要更新其子菜单的状态,然后将结果设置回 的UIBarButtonItem属性menu。请参阅此处:如何在运行时更改 UIMenu 内 UIAction 的状态?