SwiftUI:未在DropDelegate中删除NSString值 [英] SwiftUI: Not getting dropped NSString value in DropDelegate
本文介绍了SwiftUI:未在DropDelegate中删除NSString值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用NSString实现一个简单的拖放操作。我可以让它与NSURL一起工作,但不能与NSString一起工作。每次我尝试拖放操作时,结果总是为零。以下是我的代码:
struct ContentView: View
{
var body: some View
{
Text("Hello World")
.onDrag { NSItemProvider(object: "Hello World" as NSString) }
}
}
然后拖放的对象:
struct DroppedView: View, DropDelegate
{
var body: some View
{
Text("Drop here")
.onDrop(of: ["public.text"], delegate: self)
}
func performDrop(info: DropInfo) -> Bool
{
if let items = info.itemProviders(for: ["public.text"]).first
{
item.loadItem(forTypeIdentifier: "public.text", options: nil)
{
(data, error) in
print(data)
}
}
return true
}
}
我原本预计输出结果是&Hello World&。我错过了什么?
推荐答案
这可能是一个错误,但NSString
将自身注册为Utf-8纯文本类型提供程序(它符合Public.Text,但无法解码为),因此工作的变体是
func performDrop(info: DropInfo) -> Bool
{
if let item = info.itemProviders(for: ["public.utf8-plain-text"]).first
{
item.loadItem(forTypeIdentifier: "public.utf8-plain-text", options: nil)
{
(data, error) in
if let data = data as? Data {
print(NSString(data: data, encoding: 4) ?? "failed")
}
}
}
return true
}
使用Xcode 13/MacOS 11.5.2测试
这篇关于SwiftUI:未在DropDelegate中删除NSString值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文