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])
}
}
解决方案
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, ...])
推荐阅读
- python - 不使用搜索查询从所选频道获取*所有* Youtube 视频 ID
- rust - 如何在 Tokio 运行时上下文中从异步方法调用的非异步方法中等待未来?
- mysql - 这个 presto 查询有什么问题?
- macos - 如何解决 Big Sur 上的 CLT 问题?
- reactjs - 使用函数中的方法做出反应
- javascript - JavaScript 游戏中的设置间隔函数不是每 10 秒运行一次
- sql - 如何在 SQL 中添加更新列以添加外键
- css - 自定义钩子是最好的解决方案吗?
- python - 目标不匹配的张量流形状(cifar10)
- javascript - django模板中带有for循环的html表,需要一个表头