简体   繁体   English

SwiftUI | onDrag - 自定义 (dragItem) 预览图像外观

[英]SwiftUI | onDrag - customize (dragItem) preview image appearance

I've been wondering if there is any way to customize the preview image of the view that's being dragged when using onDrag ?我一直想知道是否有任何方法可以自定义使用onDrag时被拖动的viewpreview image

As you might see, the preview image is by default a slightly bigger opacity image of the view.如您所见,默认情况下, preview image是视图的稍大的不透明度图像。

From what I have found, a preview image is generated at the very beginning of the dragging process.根据我的发现,在拖动过程的一开始就生成了preview image But I couldn't find a way to change it.但我找不到改变它的方法。

What I mean by customizing is to have some custom image or a preview image of a custom view .我所说的自定义是指拥有一些自定义image或自定义viewpreview image (Both without the default opacity) (都没有默认的不透明度)

Does anyone have an idea?有没有人有想法?

I have tried to use previewImageHandler and in general, read a lot about the NSItemProvider .我曾尝试使用previewImageHandler并且一般来说,阅读了很多关于NSItemProvider But for me, it seems like this is something that is not possible for SwiftUI yet?但对我来说,这似乎对 SwiftUI 来说是不可能的?

With UIKit one could have just customized the UIDragItem - something like that using previewProvider : Here使用UIKit可以自定义UIDragItem - 使用previewProvider类似的东西: 这里

Here is my demo code:这是我的演示代码:

struct ContentView: View {
    
    var body: some View {
        DraggedView()
            .onDrag({ NSItemProvider() })
    }
    
    
    private struct DraggedView: View {
    
        var body: some View {
            RoundedRectangle(cornerRadius: 20)
                .frame(width: 120, height: 160)
                .foregroundColor(.green)
        }
    }
}

I will use this for drag and drop within a LazyVGrid , so custom gestures are unfortunately no option.我将使用它在LazyVGrid进行拖放,因此遗憾的是无法选择自定义gestures

One second idea I had would be to have a gesture simultaneously that first changes the item to be dragged to something else and then onDrag starts and returns the NSItemProvider with the preview image which would be then the one I would want.我的第二个想法是同时有一个手势,首先将要拖动的item更改为其他内容,然后onDrag启动并返回带有preview imageNSItemProvider ,这将是我想要的图像。 But I couldn't have those two gestures go at the same time, you would have to dismiss one first in order to start the second.但是我不能让这两个手势同时进行,你必须先关闭一个才能开始第二个。

Thank you!谢谢!

iOS 15 adds an API to do this - you can specify the View to use for the preview . iOS的15增加了一个API来做到这一点-你可以指定View要用于preview onDrag(_:preview:) onDrag(_:预览:)

RoundedRectangle(cornerRadius: 20)
    .frame(width: 120, height: 160)
    .foregroundColor(.green)
    .onDrag {
        NSItemProvider()
    } preview: {
        RoundedRectangle(cornerRadius: 18)
            .frame(width: 100, height: 140)
            .foregroundColor(.green)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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