UIEditMenuInteraction
An interaction that provides edit operations using a menu.
Declaration
@MainActor class UIEditMenuInteractionMentioned in
Overview
Edit menu interactions provide edit actions — such as cut, copy, and paste — for the content a view displays. The presentation style the interaction uses to display the actions conforms to the input method of the interaction. For touch interactions, the actions display in an editing menu. When responding to a secondary click on devices with pointer-based input, the actions display in a context menu.
Standard UIKit classes, such as UITextView and UITextField, are preconfigured to use edit menu interactions.
To add an edit menu interaction to a generic view:
Create an edit menu interaction object, and pass an optional delegate into the default initializer.
Call the addInteraction(_:) method on your view to add the interaction.
Create a gesture recognizer to trigger the interaction and add it to the view.
The following example creates an edit menu interaction triggered by a long press.
override func viewDidLoad() {
super.viewDidLoad()
// Add the edit menu interaction.
editMenuInteraction = UIEditMenuInteraction(delegate: self)
interactionView.addInteraction(editMenuInteraction!)
// Create the gesture recognizer.
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress(_:)))
longPress.allowedTouchTypes = [UITouch.TouchType.direct.rawValue as NSNumber]
interactionView.addGestureRecognizer(longPress)
}
@objc func didLongPress(_ recognizer: UIGestureRecognizer) {
let location = recognizer.location(in: self.view)
let configuration = UIEditMenuConfiguration(identifier: nil, sourcePoint: location)
if let interaction = editMenuInteraction {
// Present the edit menu interaction.
interaction.presentEditMenu(with: configuration)
}
}By default, an edit menu interaction generates a menu that includes commands for the standard edit actions your view implements. For more information on these actions, see UIResponderStandardEditActions. You can use the interaction’s delegate to add additional items to the menu and set the target rectangle to display around using methods in the UIEditMenuInteractionDelegate protocol. For text views, you can specify the items the menu displays for specific text ranges using methods from the UITextViewDelegate, UITextFieldDelegate, or UITextInput protocols.