Hemanth
Hemanth

Reputation: 1

NavigationStack causing view to reappear before going to another view

What i want to do
1. HomeView -> DetailView
2. HomeView -> PopularMoviesView -> DetailView

The first happens with no issue but while doing the second homeview to popularMoviesView is okay but from there to detail View when i try to navigate again the popular view reappears and when i hit back the moviedetailview is there.

What's happening now is

1. HomeView -> DetailView
2. HomeView -> PopularMoviesView -> PopularMoviesView -> DetailView

//HomeView

struct HomeView: View {

    @State var moviesListViewModel = MoviesListViewModel()   
    
    var body: some View {
        NavigationStack{
            ZStack {
                Color.black.opacity(0.9)
                    .ignoresSafeArea(edges: .all)
                VStack {
                    ScrollView{
                        MoviesScrollView()
                            .environment(moviesListViewModel)
                    }
                    .frame(maxWidth:.infinity,maxHeight:.infinity,alignment: .topLeading)
                }
                .navigationDestination(for: Movie.self, destination: { item in
                    MovieDetailView(movieDetails: item)
                        .navigationBarBackButtonHidden()
                })
            }
        }
        
    }
}

//MovieDetailView

struct MovieDetailView: View {
    
    @State var videoPlayerViewModel = VideoPlayerViewModel()
    @State var movieCastViewModel = MovieCastViewModel()
    
    let movieDetails:Movie
    
    @Environment(\.dismiss) var dismiss
    
    init(movieDetails: Movie) {
        self.movieDetails = movieDetails
        print("Movie Detail Screen")
    }

    var body: some View {
        
        ZStack{
            Color(.black.opacity(0.9))
                .ignoresSafeArea()
        
            VStack {
                
                HStack{
                    Image(systemName: "arrow.left")
                        .onTapGesture {
                            dismiss()
                        }
                    Text(movieDetails.originalTitle)
                        .multilineTextAlignment(.leading)
                        .lineLimit(1)
                    
                }
                .frame(maxWidth: .infinity,alignment:.leading)
                .padding(.leading)
                .foregroundStyle(.white)
                .bold()
                .font(.title2)
                
                ScrollView(.vertical){
                    VStack{
                        VStack(spacing:0) {
                            Text(movieDetails.originalTitle)
                                .font(.largeTitle)
                                .padding(.bottom,5)
                                .padding(.top,25)
                                .frame(maxWidth: .infinity,alignment:.leading)
                            
                            HStack{
                                Text(movieDetails.releaseDate)
                                Text(movieDetails.adult ? "Rated" : "Not Rated")
                                    .frame(maxWidth: .infinity,alignment:.leading)
                                
                            }
                            
                            .foregroundStyle(.gray)
                        }
                        .frame(maxWidth: .infinity,alignment:.leading)
                        .padding(.leading)
                        .bold()
                        
                        
                        ExtractedVideoView()
                            .environment(videoPlayerViewModel)
                        
                        
                        HStack{
                            LazyImage(source: "https://image.tmdb.org/t/p/w500/\(movieDetails.posterPath)") { state in
                                if let image = state.image{
                                    image
                                        .resizingMode(.aspectFit)
                                        .aspectRatio(contentMode: .fill)
                                }
                            }
                            .scaledToFill()
                            .frame(width: 150)
                            //.frame(maxHeight: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/,alignment:.topLeading)
                            NavigationLink(value: movieDetails.overview) {
                                Text(movieDetails.overview)
                                    .multilineTextAlignment(.leading)
                                    .fixedSize(horizontal: false, vertical: true)
                                    .frame(maxWidth: .infinity,alignment:.leading)
                                    .frame(width: 200,height: 200)
                                    .foregroundStyle(.white)
                                    .lineLimit(6)
                            }
                        }
                      
                        .padding(.top)
                        .padding(.horizontal)
                        
                        HStack {
                            Spacer()
                            VStack{
                                Image(systemName: "star.fill")
                                    .foregroundStyle(Color("yellowColor"))
                                    .bold()
                                    .font(.title2)
                                Text("\(String(format: "%.1f", movieDetails.voteAverage))/10")
                                    .bold()
                                    .font(.title2)
                                Text("\(movieDetails.voteCount)")
                                    .foregroundStyle(.gray)
                                //Text("\(movieDetails.id)")
                            }
                          
                            Spacer()
                            
                            VStack{
                                Image(systemName: "star")
                                Text("Rate this")
                                    .padding(.bottom)
                            }
                            
                            .font(.title2)
                            .foregroundStyle(.blue)
                            Spacer()
                        }
                        
                        HeadingView(title: "Cast", subTitle: "Cast For This Movie")
                        
                        CastView()
                            .environment(movieCastViewModel)
                    }
                    .navigationDestination(for: String.self, destination: { overview in
                        SummaryView(summanry: overview)
                    })
                    .foregroundStyle(.white)
                    .frame(maxWidth: .infinity,maxHeight: .infinity,alignment:.topLeading)
                }
                .scrollContentBackground(.hidden)
                .scrollIndicators(.hidden)
            }
            
            
        }
        .task{
            Task{
                try await videoPlayerViewModel.getVideoDetails(videoID: movieDetails.id)
                try await movieCastViewModel.getMovieCastList(movieID: movieDetails.id)
            }
        }
        .onAppear{
            print(movieDetails.posterPath)
        }
        .navigationBarBackButtonHidden()
        
        
    }
    
}

//PopularMoviesView

struct PopularMovies: View {
   
    
    init(){
        print("Poppular Movies Screen")
    }
 
    
    @State var isLoading:Bool = true
    @State var pageNumber:Int = 1
    @Environment(MoviesListViewModel.self) var moviesListViewModel
    @Environment(\.dismiss) var dismiss
    var body: some View {
        ZStack{
            Color.black.opacity(0.9)
                .ignoresSafeArea(edges: .all)
            //if !isLoading{
            VStack{
                HStack{
                    Image(systemName: "arrow.left")
                        .imageScale(.large)
                        .onTapGesture {
                            dismiss()
                        }
                    Text("Popular movies")
                        .font(.title2)
                    
                    Spacer()
                    
                    HStack{
                        
                        if pageNumber > 1{
                            Button {
                                pageNumber -= 1
                                Task{
                                    
                                    try await moviesListViewModel.getAllPopularMoviesList(page: pageNumber)
                                }
                            } label: {
                                
                                Image(systemName: "arrow.left")
                                
                            }
                            .disabled(pageNumber<1 ? true : false)
                        }
                        
                        Text("\(pageNumber)")
                        
                        Button {
                            pageNumber += 1
                            Task{
                                try await moviesListViewModel.getAllPopularMoviesList(page: pageNumber)
                            }
                        } label: {
                            
                            Image(systemName: "arrow.right")
                            
                        }
                    }
                    .bold()
                    .foregroundStyle(Color("yellowColor"))
                    .padding(.trailing)
                    
                }
                .foregroundStyle(.white)
                .bold()
                .frame(maxWidth: .infinity,alignment:.leading)
                .padding(.leading)
                
                ScrollView(.vertical){
                    if isLoading != true {
                        LazyVStack(spacing: 10) {
                            ForEach(moviesListViewModel.movieAllPopularListArray, id: \.id) { data in
                                if let results = data.results {
                                    ForEach(results, id: \.uniqueID) { innerData in
                                        NavigationLink(value:innerData){
                                            MovieCard2(imageURL: innerData.posterPath, rating: innerData.voteAverage, movieTitle: innerData.title, releaseDate: innerData.releaseDate, viewersCount: innerData.voteCount)
                                            
                                            Divider()
                                                .background(Color.gray)
                                        }
                                    }
                                }
                            }
                        }
                        .padding(.leading)
                    }
                    else{
                        ProgressView("Loading...")
                            .controlSize(.large)
                            .foregroundStyle(Color("yellowColor"))
                    }
                }
            }
            .scrollContentBackground(.hidden)
            .navigationBarBackButtonHidden()
            .frame(maxWidth: .infinity,alignment:.leading)
            .scrollIndicators(.hidden)
            
        }
        .task {
            Task{
                try await moviesListViewModel.getAllPopularMoviesList(page: pageNumber)
            }
        }
        .onChange(of: moviesListViewModel.isLoading) { oldValue, newValue in
            isLoading = newValue
        }
    }
}

Upvotes: 0

Views: 51

Answers (1)

malhal
malhal

Reputation: 30569

In SwiftUI the View struct is the view model already so just remove the unnecessary MoviesListViewModel etc. and it should work fine.

Upvotes: 0

Related Questions