Last active
January 6, 2021 13:11
-
-
Save zahmedpk/9c92387cc107f945f7e452940b7256e7 to your computer and use it in GitHub Desktop.
How to drag and drop text from one view to another view within an app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Xcode 12.3 | |
import SwiftUI | |
class ViewModel: ObservableObject { | |
@Published var itemsInUpperStack: [String] = ["Drag me down", "Some more text"] | |
@Published var itemsInLowerStack: [String] = ["Drag me up", "one two three"] | |
func move(item: String) { | |
if !itemsInLowerStack.contains(item) { | |
itemsInLowerStack.append(item) | |
} | |
if !itemsInUpperStack.contains(item) { | |
itemsInUpperStack.append(item) | |
} | |
} | |
} | |
struct ContentView: View { | |
@ObservedObject var viewModel = ViewModel() | |
var body: some View { | |
TextContainer(viewModel: viewModel, items: viewModel.itemsInUpperStack) | |
TextContainer(viewModel: viewModel, items: viewModel.itemsInLowerStack) | |
} | |
} | |
struct TextContainer: View { | |
let viewModel: ViewModel | |
let items: [String] | |
var body: some View { | |
HStack(spacing: 10) { | |
ForEach(items, id: \.self){ | |
item in | |
Text(item) | |
.font(.title) | |
.frame(maxWidth: .infinity, maxHeight: .infinity) | |
.background(Color.randomColor(withAlpha: 0.3)) | |
.onDrag({ | |
NSItemProvider(object: item as NSString) | |
}) | |
} | |
} | |
.onDrop(of: ["public.text"], isTargeted: nil, perform: { (providers) -> Bool in | |
if let firstProvider = providers.first { | |
_ = firstProvider.loadObject(ofClass: String.self) { (providerReading, error) in | |
if providerReading != nil { | |
print("provider reading is ", providerReading!) | |
DispatchQueue.main.async { | |
self.viewModel.move(item: providerReading!) | |
} | |
} | |
} | |
return true | |
} | |
return false | |
}) | |
.padding() | |
.addDashedBorder() | |
.padding() | |
} | |
} | |
extension View { | |
func addDashedBorder() -> some View { | |
self | |
.overlay(RoundedRectangle(cornerRadius: 10).stroke(style: StrokeStyle(lineWidth: 10, dash: [20]))) | |
} | |
} | |
extension Color { | |
static func randomColor(withAlpha alpha: CGFloat) -> Color { | |
let randomUIColor = UIColor(red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: alpha) | |
return Color(randomUIColor) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment