UIBarButtonItem
和 UIButton
是 iOS 开发中常用的 UI 组件。UIBarButtonItem
通常用于导航栏或工具栏,而 UIButton
则用于用户点击操作。UIMenu
是 iOS 13 及以上版本中引入的一个新特性,用于在长按按钮或视图时显示上下文菜单。
首先,你需要创建自定义的 UIMenuItem
对象,并设置其标题和动作。
let customMenuItem = UIMenuItem(title: "Custom Action", action: #selector(customAction(_:)))
然后,你可以创建一个 UIMenu
对象,并将自定义菜单项添加到其中。
let customMenu = UIMenu(title: "Custom Menu", children: [customMenuItem])
对于 UIButton
,你需要设置其 menu
属性:
button.menu = customMenu
对于 UIBarButtonItem
,你需要将其包装在一个 UIContextMenuInteraction
中:
let interaction = UIContextMenuInteraction(delegate: self)
view.addInteraction(interaction)
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
return customMenu
}
}
以下是一个完整的示例,展示了如何为 UIButton
和 UIBarButtonItem
设置自定义菜单。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.setTitle("Long Press Me", for: .normal)
button.frame = CGRect(x: 50, y: 100, width: 150, height: 50)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
view.addSubview(button)
let customMenuItem = UIMenuItem(title: "Custom Action", action: #selector(customAction(_:)))
let customMenu = UIMenu(title: "Custom Menu", children: [customMenuItem])
button.menu = customMenu
}
@objc func buttonTapped() {
print("Button tapped")
}
@objc func customAction(_ sender: UIMenuItem) {
print("Custom action performed")
}
}
import UIKit
class ViewController: UIViewController, UIContextMenuInteractionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let barButtonItem = UIBarButtonItem(title: "Right Click Me", style: .plain, target: nil, action: nil)
navigationItem.rightBarButtonItem = barButtonItem
let interaction = UIContextMenuInteraction(delegate: self)
view.addInteraction(interaction)
}
func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
let customMenuItem = UIMenuItem(title: "Custom Action", action: #selector(customAction(_:)))
let customMenu = UIMenu(title: "Custom Menu", children: [customMenuItem])
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
return customMenu
}
}
@objc func customAction(_ sender: UIMenuItem) {
print("Custom action performed")
}
}
通过以上方法,你可以轻松地为 UIBarButtonItem
和 UIButton
设置自定义菜单,并根据需要添加或修改菜单项。
领取专属 10元无门槛券
手把手带您无忧上云