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)
您应该使用ViewModifier
viaphotosPicker(ispresented:selection:matching:preferreditemencoding:)
而不是View
照片选择器的版本。
这样,您可以创建一个 Button,其中:
@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)
归档时间: |
|
查看次数: |
254 次 |
最近记录: |