You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI自定义Transferable类型与UTI/UTType的DropDestination失效问题

问题描述

操作演示图

我尝试在App中通过Transferable协议实现拖拽功能,参照教程操作后仍无法正常工作,即使编写了极简示例代码依旧失效,怀疑遗漏了某个简单的关键步骤。

界面截图

示例代码

import SwiftUI
import Foundation
import UniformTypeIdentifiers

struct ContentView: View {

    @State private var draggedOutput: String = ""
    var body: some View {
    VStack(spacing: 50) {
        Text("Text")
            .font(.title)
            .draggable("DRAGGED TEXT")
        Text("Custom Transferable")
            .font(.title)
            .draggable(CustomTransferable())
        Divider()
        Text(draggedOutput)
            .font(.largeTitle)
            .frame(width: 250, height: 250)
            .background(Color.green)
            .dropDestination(for: String.self) { items, location in
                draggedOutput = items.first!
                return true
            }
            .dropDestination(for: CustomTransferable.self) { items, location in
                draggedOutput = items.first!.id.uuidString
                return true
            }
    }
    .padding()
}
}


struct CustomTransferable: Identifiable, Codable, Transferable {

    static var transferRepresentation: some TransferRepresentation {
    CodableRepresentation(for: CustomTransferable.self, contentType: UTType(exportedAs: "com.gmail.Me.D.ExtraInfoAudio"))
}

let id: UUID

init(id: UUID = UUID()) {
    self.id = id
}
}
解决方法

1. 声明自定义UT类型到Info.plist

你使用了自定义UTType com.gmail.Me.D.ExtraInfoAudio,但未在项目Info.plist中声明该导出类型,导致系统无法识别该类型的拖拽数据。

打开项目的Info.plist,添加如下配置(可直接以源代码模式粘贴):

<key>UTExportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeIdentifier</key>
        <string>com.gmail.Me.D.ExtraInfoAudio</string>
        <key>UTTypeDescription</key>
        <string>Custom Transferable Object</string>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.data</string>
        </array>
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key>
            <string>customobj</string>
        </dict>
    </dict>
</array>

2. 确认部署目标版本

Transferable协议仅支持iOS 16.0+、macOS 13.0+,请确保你的项目部署目标版本不低于上述要求。

3. 可选:添加拖拽预览(提升交互体验)

可以给自定义类型的拖拽操作添加预览视图,让用户更直观看到拖拽状态:

Text("Custom Transferable")
    .font(.title)
    .draggable(CustomTransferable()) {
        Text("拖拽中...")
            .font(.caption)
            .padding()
            .background(Color.blue.opacity(0.2))
            .cornerRadius(8)
    }

完成以上步骤后,String和自定义CustomTransferable类型的拖拽功能即可正常工作,拖入绿色区域后会正确更新显示内容。

内容的提问来源于stack exchange,提问作者KevinF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:41:05