美文网首页
Mac Catalyst 菜单栏

Mac Catalyst 菜单栏

作者: hxxxs | 来源:发表于2023-09-06 13:06 被阅读0次

    1. 系统默认菜单栏

    创建项目后运行,默认的样子


    image.png

    2. 自定义菜单栏

    通常情况下系统默认的菜单栏无法满足项目需求,例如需要添加一个特殊的菜单项,或者删除默认菜单中的菜单项等等。

    通过在AppDelegate中重写buildMenu(with builder: UIMenuBuilder)方法实现自定义菜单栏

    #if targetEnvironment(macCatalyst)
    extension AppDelegate {
        
        override func buildMenu(with builder: UIMenuBuilder) {
            ...
        }
    }
    #endif
    
    

    2.1 删除默认菜单栏

            //  删除文件菜单
            builder.remove(menu: .file)
            //  删除编辑菜单
            builder.remove(menu: .edit)
            //  删除应用菜单下的服务菜单
            builder.remove(menu: .services)
    

    运行结果


    image.png

    2.2 往默认菜单栏中插入菜单

            let keyMenu = UIMenu(title: "键盘按键", options: .displayInline, children: [
                UIKeyCommand(title: "1",
                             action: #selector(command1Action),
                             input: "1",
                             modifierFlags: .command),
                UIKeyCommand(title: "P",
                             action: #selector(commandAndShiftPAction),
                             input: "P",
                             modifierFlags: [.command, .shift])
            ])
            builder.insertChild(keyMenu, atStartOfMenu: .window)
    
    ...
    
    @objc private func command1Action() {
        print("command + 1")
    }
        
    @objc private func commandAndShiftPAction() {
        print("command + shift + P")
    }
    

    运行结果


    image.png

    2.3 新增菜单

            let newWindowMenu = UIMenu(title: "新窗口", options: .destructive, children: [
                UICommand(title: "缩放", action: #selector(scaleAction)),
                UIKeyCommand(title: "关闭", action: #selector(closeAction), input: "W", modifierFlags: .command)
            ])
            builder.insertSibling(newWindowMenu, afterMenu: .application)
    
    ...
    @objc private func scaleAction() {
        print("缩放")
    }
        
    @objc private func closeAction() {
        print("关闭")
    }
    

    运行结果


    image.png

    3. 菜单栏本地化后不展示中文名称

    需要修改Build Settings -> Product Name


    image.png

    项目地址

    https://gitee.com/Hxxxs/mac-catalyst-menu

    相关文章

      网友评论

          本文标题:Mac Catalyst 菜单栏

          本文链接:https://www.haomeiwen.com/subject/bcykvdtx.html