gpt4 book ai didi

swift - SwiftUI 中的 ImagePicker

转载 作者:行者123 更新时间:2023-12-04 10:55:34 27 4
gpt4 key购买 nike

我正在尝试在 SwiftUI 中创建一个图像选择器,如下 this tutorial .基本上,这个想法是当用户点击屏幕上的灰色矩形时,会出现一个图像选择器。当他们选择一个图像时,它被导入到灰色矩形中。
问题是,当我运行代码时,出现以下错误:Thread 1: Fatal error: Reading Environment<Binding<PresentationMode>> outside View.body这出现在线parent.presentationMode.wrappedValue.dismiss()在图像选择器结构中。
我的代码如下所示:
图像选择器


struct ImagePicker: UIViewControllerRepresentable {

@Environment(\.presentationMode) var presentationMode
@Binding var image: UIImage?

class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let parent: ImagePicker

init(_ parent: ImagePicker) {
self.parent = parent
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let uiImage = info[.originalImage] as? UIImage {
parent.image = uiImage
}

parent.presentationMode.wrappedValue.dismiss()
}
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}


func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}

func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {

}
}
内容 View
import SwiftUI

struct ContentView: View {

@State private var image: Image?
@State private var showingImagePicker = false
@State private var inputImage: UIImage?


var body: some View {
NavigationView {
ZStack {
Rectangle()
.fill(Color.secondary)

if image != nil {
image?
.resizable()
.scaledToFit()
} else {
Text("Tap to select a picture")
}
}
.onTapGesture {
self.showingImagePicker = true
}


.sheet(isPresented: $showingImagePicker, onDismiss: loadImage) {
ImagePicker(image: self.$inputImage)
}
}
}

func loadImage() {
guard let inputImage = inputImage else { return }
image = Image(uiImage: inputImage)
}

}
类似于推荐的解决方案 here ,我尝试更换 @Environment(\.presentationMode) var presentationMode@Binding var isPresented: Bool在图像选择器结构中并替换麻烦的行 parent.presentationMode.wrappedValue.dismiss()parent.isPresented = false .
然而,这导致了一个不同的问题——当工作表被解散时图像没有加载(我猜是因为我没有在任何地方调用 dismiss() 方法)。
我对 Swift 和编码很陌生,所以如果我能在任何地方更简洁地解释并随时进行更正,我深表歉意。

最佳答案

好的,看起来您正在测试 13.1 -> 更新到 13.2 - 它可以工作

关于swift - SwiftUI 中的 ImagePicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59227158/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com