[英]SwiftUI drag from one list to another list
我正在嘗試在列表之間拖放。
我試過的:
我在 UIKIt 和使用 UIViewControllerRepresentable 中找到了一個解決方案。 但這不是我想要的。
另一個解決方案是使用列表中的.onDrag {},但它適用於 iPad,但不適用於 iPhone。
如何在 iPhone 上的兩個列表之間移動項目?
看一下這個:
但是->正如您所寫,它不適用於列表(僅在 iPad 上),您可以使用 VStack 從左到右或從右到左拖動。
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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.