Search code examples
swiftuiviewcontrollerdraggable

How to make object that is being dragged the foreground object


I am working on an app that has users drag objects to target locations. Everything thus far is programmatically created, aka no storyboard. My issue is that for the draggable objects, the colored circles on the right, when dragged over the target area, they are behind the target area. Is there a way for it to be the foreground object?

Here is a picture: currentAppSetup


Solution

  • I think the bringSubviewToFront(_:) is what will help you here, more info on this from the docs

    As soon as the view is selected, you can do something like:

    parentView.bringSubviewToFront(viewBeingDragged)
    

    This should make the view being dragged the top most view in that parent / container view

    Give this is a go and see if this helps your use case

    If you want more customization, that is, you want to specify the draggable views above some views but below some others, you could look at insertSubview(_:aboveSubview:) and some other similar methods.