如何知道 PhotosPicker 何时出现?

irr*_*oss 1 swiftui photospicker

当用户调用 PhotosPicker 时,我需要直接运行一些代码。我尝试过 .onAppear 和 .onTapGesture,但是当点击打开 PhotosPicker 视图的按钮时,这些方法永远不会被触发。

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
                            }
                        }
                    }
Run Code Online (Sandbox Code Playgroud)

iSp*_*n17 6

您应该使用ViewModifierviaphotosPicker(ispresented:selection:matching:preferreditemencoding:)而不是View照片选择器的版本。

这样,您可以创建一个 Button,其中:

  • 首先,您想在呈现照片选择器时添加 TapGesture 处理程序吗?
  • 其次,将处理照片选择器呈现的绑定设置为 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)
}
Run Code Online (Sandbox Code Playgroud)