13 C
New York
Monday, March 17, 2025

ios – Easy methods to navigate to a NavigationDestination when a variable is now not empty, and navigateBack when it’s empty


I’ve an app that makes use of a Photospicker to permit the person to pick pictures and think about them in a PhotosView: that is the viewModel for choosing the pictures:

@MainActor
@Observable
closing class PhotosPickerViewModel {
    
    var selectedImages: [UIImage] = []
  
    var imageSelections: [PhotosPickerItem] = [] {      //momentary Photoitems the person selects
        didSet {
            setImages(from: imageSelections)        //when it modifications convert these gadgets into imageSelections
        }
    }
    
    //Flip the PhotosPickerItem right into a UIimage we are able to use in views
    personal func setImages(from picks: [PhotosPickerItem]) {
        
        Process {
            var photographs: [UIImage] = []
            for choice in picks {
                if let knowledge = strive? await choice.loadTransferable(kind: Information.self) {
                    if let uiImage = UIImage(knowledge: knowledge) {
                        photographs.append(uiImage)
                        
                    }
                }
            }
           selectedImages = photographs
            
          
        }
        
    }
    
}

and in my foremost view I’m utilizing an if else to indicate views primarily based on that property:

if photosPickerViewModel.selectedImages.isEmpty {}
else {
        PhotosView(selectedImages: photosPickerViewModel.selectedImages)
     }

And that is the PhotosView:

struct PhotosView: View {
    
    let selectedImages: [UIImage]
    @State personal var selectedImageIndex: Int = 0
    
    var physique: some View {
        VStack {
            if selectedImages.isEmpty  {        //Catch the Error Right here and Present it to the person
                Textual content("ERROR: No Picture Handed in")
            } else {
                Spacer()
                PhotosTabView(selectedImages: selectedImages, selectedImageIndex: $selectedImageIndex)
                Spacer()
                ImagesScrollView(selectedImages: selectedImages, selectedImageIndex: $selectedImageIndex)
            }
        }
        .edgesIgnoringSafeArea(.all)   
    }
}

My query Is how would I exchange this if else verify with a NavigationStack and navigate to PhotosView as quickly as a selectedImages isn’t empty after which navigate again when it’s empty.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles