我的图像选择器在两个方向上都可以与照片库一起使用,但是使用相机它不能正确调整为横向。
这是我的代码:
File1, UIViewControllerRepresentable:
import UIKit
import SwiftUI
struct ImagePicker: UIViewControllerRepresentable {
var sourceType: UIImagePickerController.SourceType = .photoLibrary
@Binding var selectedImage: UIImage
@Environment(\.presentationMode) private var presentationMode
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = sourceType
imagePicker.delegate = context.coordinator
return imagePicker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<ImagePicker>) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var parent: ImagePicker
init(_ parent: ImagePicker) {
self.parent = parent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
parent.selectedImage = image
}
parent.presentationMode.wrappedValue.dismiss()
}
}
}
文件2,使用它:
.fullScreenCover(isPresented: $isShowPhotoLibrary) {
ImagePicker(sourceType: .camera, selectedImage: self.$image)
}
我不固定使用全屏覆盖,只是这样做是因为它至少部分起作用。
如果有人能提供帮助,我将不胜感激。
可能有一个变通解决方案,但根据 Apple 文档:
“UIImagePickerController 类仅支持纵向模式。....”
https://developer.apple.com/documentation/uikit/uiimagepickercontroller
也许你可以使用:
let theCamera = AVCaptureDevice.default(for: .video)
这很好用。
解决这个问题的方法是创建一个调用您的 ImagePicker 的特定视图,并将该视图锁定为纵向模式。
首先,在 AppDelegate 中,添加这个,这是我从这个视频中学到的: https://www.youtube.com/watch?v=NNY6C9-QWCI
static var orientationLock = UIInterfaceOrientationMask.all
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppDelegate.orientationLock
}
然后,制作视图,例如ImagePickerView
import SwiftUI
struct ImagePickerView: View {
@State private var image = UIImage()
var body: some View {
ZStack {
ImagePicker(sourceType: .camera, selectedImage: $image)
}
.onAppear() {
UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
AppDelegate.orientationLock = .portrait
}
.onDisappear() {
AppDelegate.orientationLock = .all
}
}
}
struct ImagePickerView_Previews: PreviewProvider {
static var previews: some View {
ImagePickerView()
}
}
要从另一个视图调用 ImagePicker/camera,只需调用 ImagePickerView() 它应该可以正常工作