iOS16适配指南之UIMenu

2022-06-29 15:04:31 浏览数 (1)

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

代码语言:javascript复制
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
    }
}

0 人点赞