前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS14开发-菜单

iOS14开发-菜单

作者头像
YungFan
发布2021-11-24 15:03:11
7240
发布2021-11-24 15:03:11
举报
文章被收录于专栏:学海无涯学海无涯

ShortcutItem

iPhone 11 之前,有一种主屏交互方式称之为 3D Touch,现在已经改为 Haptic Touch。 它是一种立体触控技术,可感应不同的触控压力。通过该技术可以给 App 设置最多 4 个不同的 ShortcutItem(快捷操作菜单),实现方式分为静态和动态两种。

  • 静态配置通过 Info.plist 文件。
代码语言:javascript
复制
<key>UIApplicationShortcutItems</key>
<array>
    <dict>
        <key>UIApplicationShortcutItemIconType</key>
        <string>UIApplicationShortcutIconTypeSearch</string>
        <key>UIApplicationShortcutItemSubtitle</key>
        <string>副标题</string>
        <key>UIApplicationShortcutItemTitle</key>
        <string>标题</string>
        <key>UIApplicationShortcutItemType</key>
        <string>搜索</string>
    </dict>
    ...
</array>
  • 动态配置通过代码设置。
代码语言:javascript
复制
extension AppDelegate {
    func shortcutItems() {
        // 图标
        let icon1 = UIApplicationShortcutIcon(systemImageName: "qrcode.viewfinder") // 系统图片
        let icon2 = UIApplicationShortcutIcon(templateImageName: "settings") // 自定义图片
        let icon3 = UIApplicationShortcutIcon(type: .search) // 系统类型

        // 菜单
        let item1 = UIApplicationShortcutItem(type: "1", localizedTitle: "扫描", localizedSubtitle: nil, icon: icon1, userInfo: nil)
        let item2 = UIApplicationShortcutItem(type: "2", localizedTitle: "设置", localizedSubtitle: nil, icon: icon2, userInfo: nil)
        let item3 = UIApplicationShortcutItem(type: "3", localizedTitle: "搜索", localizedSubtitle: nil, icon: icon3, userInfo: nil)

        // 设置
        UIApplication.shared.shortcutItems = [item1, item2, item3]
    }
}
  • 点击事件响应。
代码语言:javascript
复制
// iOS13之前,使用AppDelegate的代理方法
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "1" {
        window?.rootViewController?.view.backgroundColor = .red
    } else if shortcutItem.type == "2" {
        window?.rootViewController?.view.backgroundColor = .green
    } else if shortcutItem.type == "3" {
        window?.rootViewController?.view.backgroundColor = .blue
    }
}

// iOS13之后,AppDelegate的代理方法不会被调用,需要使用SceneDelegate的代理方法
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "1" {
        window?.rootViewController?.view.backgroundColor = .red
    } else if shortcutItem.type == "2" {
        window?.rootViewController?.view.backgroundColor = .green
    } else if shortcutItem.type == "3" {
        window?.rootViewController?.view.backgroundColor = .blue
    }
}

UIMenu

  • UIMenu 在 iOS 13 中引入,可以很方便的创建程序菜单和上下文菜单。
代码语言:javascript
复制
import UIKit

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 显示工具条
        navigationController?.isToolbarHidden = false
        // 菜单绑定到UIBarButtonItem(iOS 14的构造函数)
        let addNewItem = UIBarButtonItem(systemItem: .add, primaryAction: nil, menu: createMenu())
        // 放到工具条
        toolbarItems = [addNewItem]
    }

    func createMenu() -> UIMenu {
        // 第一个菜单
        let favorite = UIAction(title: "Favorite", image: UIImage(systemName: "heart.fill")) { _ in
            print("favorite")
        }
        // 第二个菜单
        let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { _ in
            print("share")
        }
        // 第三个菜单
        let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { _ in
            print("delete")
        }
        // 创建菜单组
        let menuActions = [favorite, share, delete]
        // 创建UIMenu
        let addNewMenu = UIMenu(children: menuActions)

        return addNewMenu
    }
}
  • iOS 14 中引入UIDeferredMenuElement,允许异步地创建 UIMenu,可以动态配置菜单的内容。
代码语言:javascript
复制
import UIKit

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 放到导航条
        navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .add, primaryAction: nil, menu: createMenu())
    }

    func createMenu() -> UIMenu {
        // 应该是是通过网络获取,这里直接从Bundle加载
        let menuItemsForUser = Bundle.main.decode([RemoteItem].self, from: "menu.json")
        // 创建UIDeferredMenuElement
        let dynamicElements = UIDeferredMenuElement { completion in
            // 创建UIAction
            let actions = menuItemsForUser.map { item in
                UIAction(title: item.title, image: UIImage(systemName: item.icon)) { _ in
                    print("\(item.title) tapped")
                }
            }
            // 一定要调用completion处理
            completion(actions)
        }

        return UIMenu(children: [dynamicElements])
    }
}

// 菜单Model
struct RemoteItem: Codable {
    let title: String
    let icon: String
}

// 加载文件并转Model
extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to find \(file) in bundle.")
        }
        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }
        guard let model = try? JSONDecoder().decode(T.self, from: data) else {
            fatalError("Failed to decode \(file) from bundle.")
        }
        return model
    }
}

JSON内容如下:

代码语言:javascript
复制
[
    {
        "title": "Favorite",
        "icon": "heart.fill"
    },
    {
        "title": "Share",
        "icon": "square.and.arrow.up.fill"
    },
    {
        "title": "Delete",
        "icon": "trash.fill"
    }
]

Context Menus

  • WWDC 2019 推出了上下文菜单(Context Menus),也是通过按压的方式触发,不同于 3D Touch(Haptic Touch),Context Menus 一般用于 App 内菜单的设置。
  • 如果要启用上下文菜单,需要创建一个UIContextMenuInteraction并将其添加给某个触发的 UIView,然后指定 delegate,在代理方法创建 UIMenu 并返回UIContextMenuConfiguration即可。
代码语言:javascript
复制
import UIKit

class ViewController: UIViewController {    
    // 需要打开User Interaction
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 创建UIContextMenuInteraction
        let interaction = UIContextMenuInteraction(delegate: self)
        // 添加UIContextMenuInteraction
        // 换成其他UIView皆可
        imageView.addInteraction(interaction)
    }
}

// 代理方法
extension ViewController: UIContextMenuInteractionDelegate {
    func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {        
        // 第一个菜单
        let favorite = UIAction(title: "Favorite", image: UIImage(systemName: "heart.fill")) { action in
            print("favorite")
        }        
        // 第二个菜单
        let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
            print("share")
        }
        // 第三个菜单
        let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash.fill"), attributes: [.destructive]) { action in
            print("delete")
        }        
        // 返回UIContextMenuConfiguration
        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
            UIMenu(children: [favorite, share, delete])
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021/10/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ShortcutItem
  • UIMenu
  • Context Menus
相关产品与服务
图像处理
图像处理基于腾讯云深度学习等人工智能技术,提供综合性的图像优化处理服务,包括图像质量评估、图像清晰度增强、图像智能裁剪等。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档