美文网首页
swiftUI 如何读取相册

swiftUI 如何读取相册

作者: 王勋才 | 来源:发表于2021-10-07 18:56 被阅读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
    }
}



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

相关文章

网友评论

      本文标题:swiftUI 如何读取相册

      本文链接:https://www.haomeiwen.com/subject/pguznltx.html