我有.onDrag一個Image。無論我是否提供preview自己,preview總是卡在顯示Image第一次拖動時出現的內容。它NSItemProvider本身運行良好,我訪問了正確的資料,但不在preview.

一個簡單的例子(代碼在這里:https ://github.com/godbout/DragPreview )
import SwiftUI
struct AppDetail {
let bundleIdentifier: String
let icon: NSImage
init(bundleIdentifier: String) {
self.bundleIdentifier = bundleIdentifier
if
let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleIdentifier),
let representation = NSWorkspace.shared.icon(forFile: url.path).bestRepresentation(for: NSRect(x: 0, y: 0, width: 64, height: 64), context: nil, hints: nil)
{
self.icon = NSImage(size: representation.size)
self.icon.addRepresentation(representation)
} else {
self.icon = NSApp.applicationIconImage!
}
}
}
struct ContentView: View {
@State private var apps: [AppDetail] = [
AppDetail(bundleIdentifier: "com.apple.Mail"),
AppDetail(bundleIdentifier: "com.apple.MobileSMS"),
AppDetail(bundleIdentifier: "com.apple.Safari"),
]
var body: some View {
VStack(alignment: .center) {
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
.onDrag {
guard
let app = apps.first,
let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: app.bundleIdentifier)
else {
return NSItemProvider()
}
return NSItemProvider(object: url as NSURL)
} preview: {
Text(apps.first == nil ? "no app" : apps.first!.bundleIdentifier)
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
}
Button("next") {
apps.removeFirst()
}
.disabled(apps.isEmpty)
}
.frame(width: 200, height: 200)
.padding()
}
}
有什么我做錯了嗎?這可能是(另一個)SwiftUI 錯誤嗎?如果preview實際上是靜態的并且僅在第一次拖動時呈現,我該如何更改代碼以便獲得preview當前的Image?
謝謝。
uj5u.com熱心網友回復:
我在@Asperi 的評論中讀到,拖動預覽僅在初始化時創建一次。因此,如果您將 .id 添加到影像,它會強制重繪并重新初始化預覽:
Image(nsImage: apps.first == nil ? NSApp.applicationIconImage! : apps.first!.icon)
.id(apps.first?.bundleIdentifier) // here
.onDrag { ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/484313.html
