iOS 14+
Sinse iOS 14UIControl
具有提供附加菜单的点的方法
/// Return a point in this control's coordinate space to which to attach the given configuration's menu.
@available(iOS 14.0, *)
open func menuAttachmentPoint(for configuration: UIContextMenuConfiguration) -> CGPoint
因此您可以覆盖UIButton
以提供相对于按钮本身的菜单(计算或硬编码)所需的位置(`因为它在按钮的坐标空间中)并在情节提要中使用该按钮(作为控制类)或以编程方式创建(如果您需要将其注入某处):
class MyButton: UIButton {
var offset = CGPoint.zero
override func menuAttachmentPoint(for configuration: UIContextMenuConfiguration) -> CGPoint {
// hardcoded variant
// return CGPoint(x: 0, y: -50)
// or relative to orginal
let original = super.menuAttachmentPoint(for: configuration)
return CGPoint(x: original.x + offset.x, y: original.y + offset.y)
}
}
class ViewController: UIViewController {
@IBOutlet weak var btnMenuExtras: MyButton! // << from storyboard
override func viewDidLoad() {
super.viewDidLoad()
let menu = UIMenu(title: "", children: [
UIAction(title: NSLocalizedString("Gallery", comment: ""), image: UIImage(systemName: "folder"), handler: {
(_) in
// self.loadPhotoGallery()
})
])
// offset is hardcoded for demo simplicity
btnMenuExtras.offset = CGPoint(x: 0, y: -50) // << here !!
btnMenuExtras.menu = menu
}
}
结果:
使用 Xcode 13 / iOS 15 准备和测试的演示