[英]How to use the Transferable protocol in SwiftUI tables
我正在 Swift 中构建一个 macOS 应用程序,使用 SwiftUI。我有以下结构:
struct focusArticle: Identifiable {
let category: String
let headline: String
let body: String
let publishedDate: String
let source: String
var id = UUID()
}
我创建了一个数组,其中包含用于填充Table
元素的focusArticle
实例,如下所示
struct ArticleView: View {
@State private var selectedArticles = Set<focusArticle.ID>()
var body: some View {
Table(articles, selection: $selectedArticles) {
TableColumn("Category", value: \.category)
.width(70)
TableColumn("Headline", value: \.headline)
.width(350)
TableColumn("Published", value: \.publishedDate)
}
.frame(width: 600, height: 200)
}
}
我想让这个表中的每一行都可以拖动,这样我就可以从这个表中拖放到另一个视图中的类似表中。 通过阅读 Apple 的文档,我似乎需要做两件事。
focusArticle
结构符合Transferable
协议。.draggable
修饰符使元素可拖动。 我似乎无法做这两件事。 将文档中的示例代码复制到我的结构中会引发错误 — Static method 'buildBlock' requires that 'String' conform to 'TransferRepresentation'
。 将.draggable
修饰符添加到表中会引发预期错误: Instance method 'draggable' requires that '[focusArticle]' conform to 'Transferable'
编辑:这是我尝试让focusArticles
确认为 Transferable 的方法之一。
struct focusArticle: Identifiable, Codable, Transferable {
let category: String
let headline: String
let body: String
let publishedDate: String
let source: String
var id = UUID()
static var transferRepresentation: some TransferRepresentation {
CodableRepresentation(contentType: .focusArticle)
}
}
这显示错误Type 'UTType' has no member 'focusArticle'
您需要添加一个 UTType,作为这样的扩展:
extension UTType {
static var focusArticle = UTType(exportedAs: "com.yourdomain.yourapp.focusarticle")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.