我在 UINavigationController 内的 UIViewController 中将 UIButton 设置为 rightBarButtonItem,并将 iOS13 上下文菜单关联到它。
长按按钮会按预期显示上下文菜单。
有没有办法通过点击按钮来显示上下文菜单(例如,通过为 .touchUpInside 事件添加目标)?
button/barButtonItem 设置如下:
let button = UIButton(type: .system)
button.setImage(UIImage(systemName: "plus"), for: .normal)
let barButton = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = barButton
let interaction = UIContextMenuInteraction(delegate: self)
button.addInteraction(interaction)
上下文菜单定义如下:
extension ViewController: UIContextMenuInteractionDelegate {
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
let importAction = UIAction(title: "Import", image: UIImage(systemName: "folder")) { action in }
let createAction = UIAction(title: "Create", image: UIImage(systemName: "square.and.pencil")) { action in }
return UIMenu(title: "", children: [importAction, createAction])
}
}
}