Search code examples
iosswiftuiuiimage

display image from PhotoLibrary


I want to display an image selected from PhotoLibrary. The ImagePicker brings up the PhotoLibrary and I am able to select it but it wont display in the view. I have the placeholder for displaying the image with a Image(uiImage: self.image) and frame 50x50. How to update the image in the current view

struct AddContactView: View {

@State private var selectedPhoto: PhotosPickerItem?
@State private var selectedPhotoData: Data?


var body: some View {
    NavigationView {
        VStack (alignment: .leading){
            TextField("Full Name", text: $nameInput)
                .textContentType(.name)
                
            TextField("Phone Number", text: $phoneInput)
                .textContentType(.telephoneNumber)
            Spacer()
            //Text(Image(systemName: "Dummy"))
            ZStack {
                if let selectedPhotoData, let image = UIImage(data: selectedPhotoData) {
                    Image(uiImage: image)
                        .resizable()
                        .scaledToFill()
                        .frame(minWidth: 100, maxWidth: 150)
                        .edgesIgnoringSafeArea(.all)
                }
                PhotosPicker(selection: $selectedPhoto, matching: .any (of:
                        [.images, .not(.livePhotos)])) {
                            Label("Select Photo", systemImage: "photo")
                }
                .tint(.blue)
                .onChange(of: selectedPhoto) { newPhoto in
                    Task{
                        if let data = try? await newPhoto!.loadTransferable(type: Data.self) {
                            selectedPhotoData?.append(data)
                        }
                    }
                    
                }
            }

        }
         

        }
        .padding()
        .navigationTitle("Add ")
        
    }

}` before_selection after_selection After selection the image fills the screen and the select photo button moves to the center from the bottom. I want the image to go into a circle of size 64 just below my phone number text field. How can I do that.


Solution

  • try replacing .sheet and ImagePicker with .photosPicker.

    Here are some links to help with loading the transferable:

    https://developer.apple.com/documentation/photokit/photospicker (Probably needs .onChange)

    https://swiftwithmajid.com/2023/04/25/photospicker-in-swiftui/ ( use .task(id: selectedPhoto) )