快速更改 UImenu 的位置

Ric*_*ero 11 uikit ios swift uimenu

我想向我的应用程序添加一个 UIMenu,我正在练习它,现在有一个问题是否可以将其位置设置UIMenu为比按钮当前显示的位置稍高:

按钮上方的菜单

正如您在这张照片中看到的,菜单当前覆盖了选项卡栏,我想将其设置为比选项卡栏高一点。这是我的代码:

let menu = UIMenu(title: "", children: [
  UIAction(title: NSLocalizedString("Gallery", comment: ""), image: UIImage(systemName: "folder"), handler: {
    (_) in
    self.loadPhotoGallery()
  })
])

btnMenuExtras.menu = menu
Run Code Online (Sandbox Code Playgroud)

Asp*_*eri 15

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
Run Code Online (Sandbox Code Playgroud)

因此您可以覆盖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
    }
}
Run Code Online (Sandbox Code Playgroud)

演示

结果:

演示1

使用 Xcode 13 / iOS 15 准备和测试演示