首页 > 解决方案 > 快速在按钮点击时呈现上下文菜单

问题描述

在 iOS 中,上下文菜单可以通过长按或点击来显示。目前,下面的代码在长按时显示上下文菜单,如何在点击时显示菜单?

    let interaction = UIContextMenuInteraction(delegate: self)
    tagBtn.addInteraction(interaction)

    func contextMenuInteraction(_ interaction: UIContextMenuInteraction,
      configurationForMenuAtLocation location: CGPoint)
      -> UIContextMenuConfiguration? {

      let favorite = UIAction(title: "Favorite",
        image: UIImage(systemName: "heart.fill")) { _ in
        // Perform action
      }

      let share = UIAction(title: "Share",
        image: UIImage(systemName: "square.and.arrow.up.fill")) { action in
        // Perform action
      }

      let delete = UIAction(title: "Delete",
        image: UIImage(systemName: "trash.fill"),
        attributes: [.destructive]) { action in
         // Perform action
       }

       return UIContextMenuConfiguration(identifier: nil,
         previewProvider: nil) { _ in
         UIMenu(title: "Actions", children: [favorite, share, delete])
       }
    }

标签: swiftmenucontextmenu

解决方案


UIContextMenuInteraction仅用于上下文(长按)菜单。

如果您希望按钮的主要操作显示菜单,您只需创建 aUIMenu并将其直接分配给button.menu属性,然后 set button.showsMenuAsPrimaryAction = true,如下所示:

let favorite = UIAction(title: "Favorite",
  image: UIImage(systemName: "heart.fill")) { _ in
  // Perform action
}

...

let button = UIButton()
button.showsMenuAsPrimaryAction = true
button.menu = UIMenu(title: "", children: [favorite, ...])

推荐阅读