Reputation: 515
I need to run some code directly when the user invokes the PhotosPicker. I have tried .onAppear and .onTapGesture, but those methods never gets triggered when tapping the button that opens the PhotosPicker-view.
PhotosPicker(selection: $selectedItem, matching: .any(of: [.images, .not(.livePhotos)])) {
Image(systemName: "photo")
.controlSize(.large)
.foregroundColor(.white)
}
.onTapGesture {
print("--- This is never executed ---")
}
.onChange(of: selectedItem) { newItem in
Task {
if let data = try? await newItem?.loadTransferable(type: Data.self) {
selectedPhotoData = data
}
}
}
Upvotes: 1
Views: 852
Reputation: 3063
You should use the ViewModifier
via photosPicker(ispresented:selection:matching:preferreditemencoding:)
instead of the View
version of Photos Picker.
That way, you can create a Button instead, which:
@State private var selectedPhotos: [PhotosPickerItem] = []
@State private var showPhotosPicker: Bool = false
var body: some View {
VStack {
[...]
Button("Show photos picker") {
print("this will print")
self.showPhotosPicker = true
}
[...]
}
.photosPicker(isPresented: $showPhotosPicker, selection: $selectedPhotos)
}
Upvotes: 10
Reputation: 93
You have to use .simultaneousGesture(). This is because PhotoPicker itself also has a TapGesture which prevents the added gesture from being read. The .simultaneousGesture() modifier should fix that.
.simultaneousGesture(TapGesture()
.onEnded({
print("Hello")
})
)
Upvotes: 1