SwiftUI |onDrag - 自定义 (dragItem) 预览图像外观 [英] SwiftUI | onDrag - customize (dragItem) preview image appearance

查看:38
本文介绍了SwiftUI |onDrag - 自定义 (dragItem) 预览图像外观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道是否有任何方法可以自定义使用 onDrag 时被拖动的 view预览图像?

I've been wondering if there is any way to customize the preview image of the view that's being dragged when using onDrag?

如您所见,预览图像 默认情况下是视图的略大不透明度图像.

As you might see, the preview image is by default a slightly bigger opacity image of the view.

据我所知,在拖动过程的一开始就生成了一个预览图像.但我找不到改变它的方法.

From what I have found, a preview image is generated at the very beginning of the dragging process. But I couldn't find a way to change it.

我所说的自定义是指拥有一些自定义image 或自定义view预览图像.(都没有默认的不透明度)

What I mean by customizing is to have some custom image or a preview image of a custom view. (Both without the default opacity)

有人有想法吗?

我尝试使用 previewImageHandler 并且一般来说,阅读很多关于 NSItemProvider 的信息.但对我来说,这似乎是 SwiftUI 无法实现的?

I have tried to use previewImageHandler and in general, read a lot about the NSItemProvider. But for me, it seems like this is something that is not possible for SwiftUI yet?

使用 UIKit 可以自定义 UIDragItem - 类似使用 previewProvider 的东西:此处

With UIKit one could have just customized the UIDragItem - something like that using previewProvider: Here

这是我的演示代码:

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)
        }
    }
}

我将使用它在 LazyVGrid 中进行拖放,因此很遗憾没有自定义 gestures 选项.

I will use this for drag and drop within a LazyVGrid, so custom gestures are unfortunately no option.

我的第二个想法是同时有一个手势,首先将 item 更改为拖动到其他内容,然后 onDrag 启动并返回 NSItemProviderpreview image 这将是我想要的.但是我不能让这两个手势同时进行,你必须先关闭一个才能开始第二个.

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. 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.

谢谢!

推荐答案

iOS 15 添加了一个 API 来执行此操作 - 您可以指定用于 previewView.onDrag(_:preview:)

iOS 15 adds an API to do this - you can specify the View to use for the preview. onDrag(_:preview:)

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

这篇关于SwiftUI |onDrag - 自定义 (dragItem) 预览图像外观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆