iOS 14如何从UIView中呈现UIMenu

7
iOS 14的似乎可以从任何或/中呈现,但我如何从通用的中呈现它?
2个回答

3

添加交互:

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

将UIContextMenuInteractionDelegate添加到您的控制器中:
extension YourViewController: UIContextMenuInteractionDelegate {
               
      func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
            
            // Create an action for sharing
            let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { action in
                // Show system share sheet
            }
    
            // Create an action for renaming
            let rename = UIAction(title: "Rename", image: UIImage(systemName: "square.and.pencil")) { action in
                // Perform renaming
            }
    
            // Here we specify the "destructive" attribute to show that it’s destructive in nature
            let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { action in
                // Perform delete
            }
    
            // Create and return a UIMenu with all of the actions as children
            return UIMenu(title: "", children: [share, rename, delete])
        }
    }
}

现在,长按视图并查看您的菜单 :)

更多信息请参见:https://kylebashour.com/posts/context-menu-guide


8
抱歉,如果表达不够清晰。我希望能够在不使用长按的情况下呈现来自通用UIView 的菜单。请翻译此内容。 - Joel Fischer
@JoelFischer 你应该在问题中更新这些重要细节。否则,这个答案完美地解决了你当前问题中所要求的内容。 - undefined

0

目前无法直接从UIView中显示菜单。

最好的解决方法是将UIButton作为子视图添加,并使用UIButton来显示菜单。这样可以避免长按操作。

button.menu = UIMenu(title: "", image: nil, identifier: nil, options: [], children: menuActions)
button.showsMenuAsPrimaryAction = true
view.addSubview(button)
view.sendSubviewToBack(button)
//add necessary constraints to position the button as you please

注意:不要在UIButton上使用"UIContextMenuInteraction",否则需要长按。感谢@HangarRash指出这一点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接