首页 > 解决方案 > 如何让 swiftui drop 委托被调用

问题描述

我希望你能帮忙。我正在尝试在 iOS 14 上的 SwiftUI 中实现纯文本的拖放。文本正在从浏览器中拖放到 TextEditor 上。文本被拖动正常,并且在放置时出现在 TextEditor 中,但没有调用委托函数。

如果您有任何想法或我可以在哪里寻找答案,我将不胜感激。

我的代码基本上是这样的:

import SwiftUI

struct ContentView: View {
    @State private var entityText = ""
    
    var body: some View {
        VStack(alignment: .leading) {

            TextEditor(text: $entityText)
                .onDrop(of: [.text], delegate: MyDropDelegate())
                .border(Color.black, width: 1)
                .padding( 60.0)
        }
    }
}

struct MyDropDelegate: DropDelegate {
    
    init() {
        print("*** INIT ")
    }
    
    func performDrop(info: DropInfo) -> Bool {
        print("*** Dropped \(info)")
        guard info.hasItemsConforming(to: [.text]) else {
            return false
        }
        return true
    }
    
    func validateDrop(info: DropInfo) -> Bool {
        print("*** Validate")
        return info.hasItemsConforming(to: [.text])
    }
    
    func dropEntered(info: DropInfo) {
        print("*** ENTERED")
    }
}

标签: swiftuidrag-and-dropios14

解决方案


正如亚当在评论中提到的那样,TextEditor 可能会发生冲突。但是 Delegate 应该设置为 self 或 observable 对象。您正在为需要引用的参数实例化某些东西。


推荐阅读