iOS開發之UIMenu

yungfan· 2020-07-26

iOS 13 引入

UIMenu 在 iOS 13 中引入,可以很方便的創建程序菜單和上下文菜單。

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: createMenuIOS13()) 
        // 放到工具條       
        toolbarItems = [addNewItem]
    }

    func createMenuIOS13() -> 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]

        let addNewMenu = UIMenu(
            title: "",
            children: menuActions)

        return addNewMenu
    }
}

參考:iOS開發之Context Menus

iOS 14 增強

iOS 14 中引入UIDeferredMenuElement,允許異步地創建 UIMenu,也就是說可以動態在后臺配置菜單的內容。

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // 放到導航條
        navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .add, primaryAction: nil, menu: createMenuIOS14())
    }

    func createMenuIOS14() -> 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(
            title: "",
            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.")
        }

        let decoder = JSONDecoder()

        guard let model = try? decoder.decode(T.self, from: data) else {
            fatalError("Failed to decode \(file) from bundle.")
        }

        return model
    }
}

JSON文件內容如下:

[
    {
        "title": "Favorite",
        "icon": "heart.fill"
    },
    {
        "title": "Share",
        "icon": "square.and.arrow.up.fill"
    },
    {
        "title": "Delete",
        "icon": "trash.fill"
    }
]

效果

源代碼

UIMenu案例

我的微信公眾號

定期發布 Swift、SwiftUI、Combine、iOS開發等技術文章,也會更新一些自己的學習心得,歡迎大家關注。

丰禾棋牌官网1369 今天吉林快三专家预测 宁夏十一选五购买 山东快乐扑克三走势图 吉林快三彩票app 股票分析网 黑龙江11选5遗漏号 江苏福彩快3开奖号码 秒速赛车官方开奖视频 进570双色球的走势图 江苏快3下载app下载安装