In addition to @Asperi's straightforward solution, I'd like to offer my modifier, which avoids to use a conditional view.
This may help in situations where you see performance issues with conditional views.
fileprivate struct Droppable: ViewModifier {
let condition: Bool
let types: [String]
var conditionalTypes: [String] { condition ? types : [] }
let tracking: Binding<Bool>?
let action: ([NSItemProvider]) -> Bool
@ViewBuilder
func body(content: Content) -> some View {
content.onDrop(of: conditionalTypes, isTargeted: tracking, perform: action)
}
}
extension View {
public func onDrop(if condition: Bool, of supportedTypes: [String], isTargeted: Binding<Bool>?, perform action: @escaping ([NSItemProvider]) -> Bool) -> some View {
self.modifier(Droppable(condition: condition, types: supportedTypes, tracking: isTargeted, action: action))
}
}
I also wrote a version for UTType
, which I prefer, because it is strongly-typed.
It enables to use the autocompleting UTType .fileURL
instead of String "public.file-url"
import UniformTypeIdentifiers.UTType
fileprivate struct Droppable: ViewModifier {
let condition: Bool
let types: [UTType]
var conditionalTypes: [UTType] { condition ? types : [] }
let tracking: Binding<Bool>?
let action: ([NSItemProvider]) -> Bool
@ViewBuilder
func body(content: Content) -> some View {
content.onDrop(of: conditionalTypes, isTargeted: tracking, perform: action)
}
}
extension View {
public func onDrop(if condition: Bool, of supportedTypes: [UTType], isTargeted: Binding<Bool>?, perform action: @escaping ([NSItemProvider]) -> Bool) -> some View {
self.modifier(Droppable(condition: condition, types: supportedTypes, tracking: isTargeted, action: action))
}
}