首页 > 解决方案 > SwiftUI onDrop 没有被调用?

问题描述

SwiftUI 的 drop API 只在特定条件下触发?

尝试将“Drag Me”块拖到其他块上。

出于某种原因,aTextEditor需要满足 2 个条件,然后它的“superview”才能检测到下降?

  1. 有一个background
  2. 禁用
struct ContentView: View {
    
    @StateObject fileprivate var viewModel = ViewModel()
    
    @State private var s1 = "Nope"
    @State private var s2 = "Nope"
    @State private var s3 = "Nope"
    @State private var s4 = "I can detect"
    @State private var s5 = "I can detect"
    @State private var s6 = "Drag me"
    
    var body: some View {
        VStack(spacing: 10) {
            TextEditor (text: $s1)  // drop not detected
                .disabled(true)
            
            TextEditor (text: $s2)  // drop not detected
                .opacity(0.5)
                .disabled(true)
            
            TextEditor (text: $s3)  // drop not detected
                .opacity(0.5).background(Color.pink.opacity(0.5))
            
            TextEditor (text: $s4) // drop detected
                .background(Color.pink.opacity(0.5))
                .disabled(true)
            
            TextEditor (text: $s5)  // drop detected
                .opacity(0.5).background(Color.pink.opacity(0.5))
                .disabled(true)
            
            Text("Yes")            // drop detected
                .background(Color.pink.opacity(0.5))
            
            TextEditor (text: $s6)
                .onDrag { () -> NSItemProvider in
                    return NSItemProvider(object: "Hello" as NSString)
                }
        }.onDrop(of: [.plainText], delegate: viewModel)
    }
}

fileprivate class ViewModel: NSObject, ObservableObject, DropDelegate {
    func dropEntered(info: DropInfo) {
        print("Drop entered: \(info)")
    }
    
    func dropUpdated(info: DropInfo) -> DropProposal? {
        print("Drop updated: \(info)")

        return DropProposal(operation: .move)
    }
    
    func dropExited(info: DropInfo) {
        print("Drop exited: \(info)")
    }
    
    func performDrop(info: DropInfo) -> Bool {
        print("Perform drop: \(info)")
        return true
    }
}

在 Xcode 12.3、iOS 14.3 上测试

我错过了什么还是这是一个错误?

标签: swiftui

解决方案


推荐阅读