我正在尝试在 iOS13 上从自定义 UIBarButtonItem 呈现 UIMenu。我无法使用 iOS 14 API。 问题是:
这是我的代码:
class CollectionViewController: UIViewController, UIContextMenuInteractionDelegate {
private lazy var sizeMenu: UIMenu = { [unowned self] in
return UIMenu(
title: "Select size",
image: nil,
identifier: nil,
options: [.displayInline],
children: [
UIAction(title: "Half", image: UIImage(systemName: "square.grid.2x2.fill"), handler: { _ in }),
UIAction(title: "Third", image: UIImage(systemName: "square.grid.3x2.fill"), handler: { _ in }),
UIAction(title: "Quarter", image: UIImage(systemName: "square.grid.4x3.fill"), handler: { _ in }),
]
)
}()
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [unowned self] suggestedActions in
return self.sizeMenu
}
}
override func viewDidLoad() {
super.viewDidLoad()
let customBarButtonItem = UIButton()
customBarButtonItem.setTitle("edit", for: .normal)
customBarButtonItem.setTitleColor(.white, for: .normal)
let interaction = UIContextMenuInteraction(delegate: self)
customBarButtonItem.addInteraction(interaction)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: customBarButtonItem)
}
}
我相信您可以使用
UIBarButtonItem(title:image:primaryAction:menu:)
轻松添加菜单。它适用于 iOS 14 及更高版本。
override func viewDidLoad() {
super.viewDidLoad()
let button = UIBarButtonItem(title: "Edit", menu: sizeMenu)
button.tintColor = .white
navigationItem.rightBarButtonItem = button
}
private lazy var sizeMenu: UIMenu = { [unowned self] in
return UIMenu(
title: "Select size",
image: nil,
identifier: nil,
options: [.displayInline],
children: [
UIAction(title: "Half", image: UIImage(systemName: "square.grid.2x2.fill"), handler: { _ in }),
UIAction(title: "Third", image: UIImage(systemName: "square.grid.3x2.fill"), handler: { _ in }),
UIAction(title: "Quarter", image: UIImage(systemName: "square.grid.4x3.fill"), handler: { _ in }),
]
)
}()