Understanding UIDragInteractionDelegate

Any time the user long-presses an item that has UIDragInteraction associated with it, a new drag session is started. This drag session uses the interaction's UIDragInteractionDelegate to obtain the data for the item that is being dragged, a drag preview, and more.

UIDragInteractionDelegate only has a single required method: dragInteraction(_:itemsForBeginning:). If you implement this method, your app can start supplying data to other apps. The return type for dragInteraction(_:itemsForBeginning:) is [UIDragItem]. UIDragItem is a container for NSItemProvider. The drag item is also responsible for providing a preview of the dragged item while it's being dragged. Normally, the selected view will be used, but sometimes you might want to provide a custom view for the preview. If this is the case, you can provide your own preview through UIDragItem.

A straightforward example of dragInteraction(_:itemsForBeginning:) looks as follows:

func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
  let text = "Hello, world"
  let provider = NSItemProvider(object: text as NSString)
  let item = UIDragItem(itemProvider: provider)
  return [item]
}

As mentioned before, users can add multiple objects to an existing drag session by tapping on them. Whenever the user taps a draggable item while a session is in progress, dragInteraction(_:itemsForAddingTo:withTouchAt:) is called on UIDragInteractionDelegate.

If you return an empty array in this method, the tapped item will not be added to the drag session. But if you return one or more UIDragItem instances, those items will be appended to the existing drag session.

A drag session can be divided into three stages:

  • The lift stage: This is the stage where the first drag item is requested, and the view that is about to be dragged is animated, so the user sees that they have started a drag session.
  • The dragging stage: The user is now moving the drag item around.
  • The end stage: Either a drop has been performed, or the drag session got canceled. If a session is canceled, the dragged item is animated back to its starting position.

You can monitor and respond to each of the stages through UIDragInteractionDelegate. To customize the lift animation, you could implement dragInteraction(_:willAnimateLiftWith:session:), for instance. For a full overview of available drag customizations, you should take a look at the documentation for UIDragInteractionDelegate; there are a bunch of methods available for you to implement!

Now that you know how to set up your app for dragging, let's see how dropping works.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.133