快速更改 UImenu 的位置

2023-11-22

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

Menu above button

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

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

btnMenuExtras.menu = menu

iOS 14+

辛斯 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
    }
}

demo

Result:

demo1

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

快速更改 UImenu 的位置 的相关文章

随机推荐