displayAsPalette
。import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
showMenuInButton()
}
func showMenuInButton() {
let button = UIButton(type: .custom)
button.setTitle("显示菜单", for: .normal)
button.setTitleColor(.systemGreen, for: .normal)
button.sizeToFit()
button.center = view.center
button.menu = createMenu()
button.showsMenuAsPrimaryAction = true
view.addSubview(button)
}
func createMenu() -> UIMenu {
// 第1个菜单
let favorite = UIAction(title: "喜欢",
subtitle: "喜欢内容",
image: UIImage(systemName: "heart"),
selectedImage: UIImage(systemName: "heart.fill"),
identifier: nil,
discoverabilityTitle: "",
attributes: [.destructive],
state: .on) { _ in
print("favorite")
}
// 第2个菜单
let share = UIAction(title: "分享",
image: UIImage(systemName: "square.and.arrow.up"),
selectedImage: UIImage(systemName: "square.and.arrow.up.fill")) { _ in
print("share")
}
// 第3个菜单
let delete = UIAction(title: "删除",
subtitle: "删除内容") { _ in
print("delete")
}
let menuElements = [favorite, share, delete]
let menu = UIMenu(title: "菜单",
subtitle: "菜单副标题",
image: UIImage(systemName: "filemenu.and.cursorarrow"),
identifier: nil,
options: [.displayInline, .displayAsPalette], // 显示模式
preferredElementSize: .large,
children: menuElements)
return menu
}
}
UIMenu与UIAction.gif