iOS进阶+实战

iOS16适配指南之UIMenu

2022-06-28  本文已影响0人  YungFan

UIMenu增加了属性preferredElementSize用于设置菜单显示时内部元素的尺寸,共有 3 种尺寸可选,分别为smallmediumlarge

import UIKit

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

        showMenuInButton()
    }

    // MARK: 给UIButton添加菜单
    func showMenuInButton() {
        let button = UIButton(type: .custom)
        button.setTitle("Open menu", for: .normal)
        button.setTitleColor(.systemGreen, for: .normal)
        button.sizeToFit()
        button.center = view.center
        button.menu = createMenu()
        button.showsMenuAsPrimaryAction = true
        view.addSubview(button)
    }

    // MARK: 创建菜单
    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")
        }
        // UIMenu支持通过preferredElementSize属性设置显示的元素尺寸
        let addNewMenu = UIMenu(title: "", preferredElementSize: .small, children: [favorite, share, delete])
        return addNewMenu
    }
}
上一篇下一篇

猜你喜欢

热点阅读