SwiftUI从一个列表拖动到另一列表 [英] SwiftUI drag from one list to another list
本文介绍了SwiftUI从一个列表拖动到另一列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试拖放到列表之间.
I am trying to drag and drop between to Lists.
我尝试过的:
我在UIKIt和使用UIViewControllerRepresentable中找到了解决方案.但这不是我想要的.
I have found a solution doing it in UIKIt and the using UIViewControllerRepresentable. But that is not what i want.
另一个解决方案是使用列表上的.onDrag {},但该解决方案在iPad上有效,而在iPhone上无效.
The other solution was using .onDrag {} on list, but that worked on iPad and didn't work on iPhone.
如何在iPhone的两个列表之间移动项目?
How to move items between two Lists on iPhone?
推荐答案
签出:
BUT->如您所写,它不适用于list(仅在iPad上)和VStack您可以从左向右或从右向左拖动.
BUT -> as you wrote, it works NOT with list (just on iPad), with VStack you can drag from left to right or right to left.
import SwiftUI
struct BookmarksList2: View {
@State private var links: [URL] = [
URL(string: "https://www.apple.com")!
]
var body: some View {
VStack {
ForEach(links, id: \.self) { url in
Text(url.absoluteString)
.onDrag {
NSItemProvider(object: url as NSURL)
}
}
.onInsert(of: ["public.url"], perform: drop)
.onDrop(
of: ["public.url"],
delegate: BookmarksDropDelegate(bookmarks: $links)
)
}
.navigationBarTitle("Bookmarks")
}
private func drop(at index: Int, _ items: [NSItemProvider]) {
for item in items {
_ = item.loadObject(ofClass: URL.self) { url, _ in
DispatchQueue.main.async {
url.map { self.links.insert($0, at: index) }
}
}
}
}
}
struct BookmarksList3: View {
@State private var links: [URL] = [
URL(string: "https://www.google.com")!
]
var body: some View {
VStack {
ForEach(links, id: \.self) { url in
Text(url.absoluteString)
.onDrag {
NSItemProvider(object: url as NSURL)
}
}
.onInsert(of: ["public.url"], perform: drop)
.onDrop(
of: ["public.url"],
delegate: BookmarksDropDelegate(bookmarks: $links)
)
}
.navigationBarTitle("Bookmarks")
}
private func drop(at index: Int, _ items: [NSItemProvider]) {
for item in items {
_ = item.loadObject(ofClass: URL.self) { url, _ in
DispatchQueue.main.async {
url.map { self.links.insert($0, at: index) }
}
}
}
}
}
struct BookmarksDropDelegate: DropDelegate {
@Binding var bookmarks: [URL]
func performDrop(info: DropInfo) -> Bool {
guard info.hasItemsConforming(to: ["public.url"]) else {
return false
}
let items = info.itemProviders(for: ["public.url"])
for item in items {
_ = item.loadObject(ofClass: URL.self) { url, _ in
if let url = url {
DispatchQueue.main.async {
self.bookmarks.insert(url, at: 0)
}
}
}
}
return true
}
}
struct ContentView : View {
var body: some View {
HStack {
BookmarksList2()
Divider()
BookmarksList3()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
这篇关于SwiftUI从一个列表拖动到另一列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文