简体   繁体   中英

Close View when .onDrag leaves view boundaries in SwiftUI

I want to close my object-menu as soon as my finger crosses the border of the view when dragging an item. CARE: I do not want to close the item when dropping the item. Unfortunately I have no idea on how to achieve this.

例子

I am simply using:

struct BuildingItemSlot: View {

    var preview: ObjectPreview
    
    var body: some View {
        VStack() {
            Image(uiImage: UIImage(contentsOfFile: preview.dataPath + "/Raw/Thumbnails/" + preview.id + ".png") ?? UIImage())
                .resizable()
                //.scaledToFit()
                .frame(width: 64, height: 64)
                .padding(4)
                //.border(Color.black, width: 1)
        }
        .onDrag({ NSItemProvider() })
    }
}

embedded in a view that makes up the inventory ...

VStack() {
     ForEach(networkManager.objectPreviewList.objects ?? []){ preview in 
             BuildingItemSlot(preview: preview)
          }
      }
      .padding(40)

I am opening and closing the side menu simply by with:

.offset(x: stateHandler.openBuildingsMenu ? 0 : 480)

Thanks a lot, Jakob

Approach:

  • Use onDrop(of:delegate) is the view modifier to be used on the view which can accept a drop.
  • The DropDelegate has functions like
    • dropEntered ,
    • dropExited ,
    • dropUpdated ,
    • validateDrop - You can dynamically validate if drop is valid or not
    • performDrop
  • Play around with above functions by adding print statements

Interruptions:

  • It is not possible to interrupt drag gestures however validateDrop should give you control when to accept / deny drop dynamically.

Reference:

Mac

iOS

Note:

  • There are some SwiftUI bugs for drag and drop for macOS and iOS, if you encounter any bugs drop a comment as it is difficult to list all the bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM