irrbloss
irrbloss

Reputation: 515

How to know when PhotosPicker is presented?

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

Answers (2)

iSpain17
iSpain17

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:

  • first of all, does the tapGesture handler you would like to add when presenting the photo picker
  • and second of all, sets the binding that handles the presentation of the photo picker to true.
@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

Torke
Torke

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

Related Questions