来自自定义 UIBarButtomItem 的 UIMenu

问题描述 投票:0回答:1

我正在尝试在 iOS13 上从自定义 UIBarButtonItem 呈现 UIMenu。我无法使用 iOS 14 API。 问题是:

  • 我需要在点击时显示菜单,而不是在长按时显示菜单(当前是在长按时)
  • 显示菜单时,我的 barButtonItem 变为白色

这是我的代码:

class CollectionViewController: UIViewController, UIContextMenuInteractionDelegate {

private lazy var sizeMenu: UIMenu = { [unowned self] in
    return UIMenu(
        title: "Select size",
        image: nil,
        identifier: nil,
        options: [.displayInline],
        children: [
            UIAction(title: "Half", image: UIImage(systemName: "square.grid.2x2.fill"), handler: { _ in }),
            UIAction(title: "Third", image: UIImage(systemName: "square.grid.3x2.fill"), handler: { _ in }),
            UIAction(title: "Quarter", image: UIImage(systemName: "square.grid.4x3.fill"), handler: { _ in }),
        ]
    )
}()

func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [unowned self] suggestedActions in
        return self.sizeMenu
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let customBarButtonItem = UIButton()
    customBarButtonItem.setTitle("edit", for: .normal)
    customBarButtonItem.setTitleColor(.white, for: .normal)
    let interaction = UIContextMenuInteraction(delegate: self)
    customBarButtonItem.addInteraction(interaction)
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: customBarButtonItem)
}
}

before tap

after tap

ios swift uikit
1个回答
0
投票

我相信您可以使用

UIBarButtonItem(title:image:primaryAction:menu:)
轻松添加菜单。它适用于 iOS 14 及更高版本。

override func viewDidLoad() {
    super.viewDidLoad()
    let button = UIBarButtonItem(title: "Edit", menu: sizeMenu)
    button.tintColor = .white
    navigationItem.rightBarButtonItem = button
}

private lazy var sizeMenu: UIMenu = { [unowned self] in
    return UIMenu(
        title: "Select size",
        image: nil,
        identifier: nil,
        options: [.displayInline],
        children: [
            UIAction(title: "Half", image: UIImage(systemName: "square.grid.2x2.fill"), handler: { _ in }),
            UIAction(title: "Third", image: UIImage(systemName: "square.grid.3x2.fill"), handler: { _ in }),
            UIAction(title: "Quarter", image: UIImage(systemName: "square.grid.4x3.fill"), handler: { _ in }),
        ]
    )
}()
© www.soinside.com 2019 - 2024. All rights reserved.