Created
December 18, 2021 18:55
-
-
Save alobaili/e731243c43f2332829825844cf4ce55b to your computer and use it in GitHub Desktop.
Simple example of using onDrop(of:delegate:)
This file contains hidden or 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
import SwiftUI | |
struct DropAcceptingView: View { | |
@State private var selectedImage: Image? | |
var body: some View { | |
ZStack { | |
Rectangle() | |
.fill(.secondary) | |
Text("You can drop an image here") | |
selectedImage? | |
.resizable() | |
.scaledToFit() | |
} | |
.aspectRatio(1, contentMode: .fit) | |
.onDrop(of: [.image], delegate: self) | |
} | |
} | |
extension DropAcceptingView: DropDelegate { | |
func performDrop(info: DropInfo) -> Bool { | |
guard info.hasItemsConforming(to: [.image]) else { return false } | |
var result = false | |
if let itemProvider = info.itemProviders(for: [.image]).first { | |
if itemProvider.canLoadObject(ofClass: UIImage.self) { | |
result = true | |
_ = itemProvider.loadObject(ofClass: UIImage.self) { reading, error in | |
if let error = error { | |
print("Error: Image drop failed - \(error)") | |
} else { | |
if let image = reading as? UIImage { | |
selectedImage = Image(uiImage: image) | |
} | |
} | |
} | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment