【问题标题】:How to get the swiftui drop delegate to be called如何让 swiftui drop 代表被调用
【发布时间】:2021-05-11 21:27:41
【问题描述】:

希望你能帮上忙。 我正在尝试在 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")
    }
}

【问题讨论】:

  • TextEditor 可能会进行自己的拖放处理,就像它自动支持剪切/复制/粘贴键盘命令一样。如果是这样,您根本不需要 onDrop。
  • 感谢@Adam 的回复。是的,它确实做了自己的丢弃处理,因为变量被填充了,但我真的希望委托事件做一些事情。没关系,我决定改变我的计划并在没有它的情况下继续工作。总有一天我会弄清楚的。感谢您的宝贵时间。

标签: swiftui drag-and-drop ios14


【解决方案1】:

正如a comment 中提到的Adam,TextEditor 可能会发生冲突。但是 Delegate 应该设置为 self 或 observable 对象。您正在为需要引用的参数实例化一些东西。

【讨论】:

  • 感谢您的回复@Ryan。我无法让它工作,所以我决定稍微改变我的设计而不使用委托。我改天再试一次。非常感谢。
猜你喜欢
  • 2012-06-10
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 2020-11-14
  • 2016-02-18
相关资源
最近更新 更多