swiftUI 如何读取相册

2021-10-07  本文已影响0人  王勋才

import SwiftUI


struct ContentView: View{
    @State var showImagePicker:Bool = false
    @State var image = UIImage()
    @State var sourceType: UIImagePickerController.SourceType = .camera
    var body: some View{
        VStack{
            Image(uiImage: image)
                .resizable()
                .scaledToFit()
                .frame(width: 400, height: 500, alignment: .center)
                .clipped()
            
            Menu(content: {
                Button(action: {
                    sourceType = .camera
                    showImagePicker.toggle()
                }) {
                   Text("拍照")
                }
                
                Button(action: {
                    sourceType = .photoLibrary
                    showImagePicker.toggle()
                }) {
                    Text("相册")
                }
               
            }, label: {
                Label("选择图片", systemImage: "photo")
            })
                .sheet(isPresented: $showImagePicker) {
                    
                    ImagePickerView(isPresented: $showImagePicker, selectedImage: $image, sourceType: $sourceType)
                        
                }
          
           
        }
    }
}


struct ImagePickerView:UIViewControllerRepresentable{
    @Binding var isPresented:Bool
    @Binding var selectedImage:UIImage
    @Binding var sourceType: UIImagePickerController.SourceType
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    class Coordinator:NSObject,UINavigationControllerDelegate,UIImagePickerControllerDelegate{
        var parent:ImagePickerView
        init(parent:ImagePickerView) {
            self.parent = parent
        }
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let selectedImage = info[.originalImage] as? UIImage{
                self.parent.selectedImage = selectedImage
                
                self.parent.isPresented = false
            }
        }
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
    
    func makeUIViewController(context: Context) -> some UIViewController {
        let controller = UIImagePickerController()
        controller.allowsEditing = true
        controller.sourceType = sourceType
        controller.delegate = context.coordinator
        return controller
    }
}



//苹果应用商店搜 王勋才 ,可以找到我全部作品。
上一篇 下一篇

猜你喜欢

热点阅读