在快速点击按钮时显示上下文菜单

Ibr*_*m99 2 contextmenu menu swift

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

Nic*_*ood 5

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

如果您希望按钮的主要操作显示菜单,您可以创建一个UIMenu并将其直接分配给button.menu属性,然后设置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, ...])
Run Code Online (Sandbox Code Playgroud)

  • 这里需要注意的是,UIButton 上的“.menu”属性适用于 iOS 14 及更高版本。 (8认同)
  • 这在 iOS 13 上不起作用。有人有 iOS13 的等效工具吗? (2认同)