Search code examples
iosswiftanimationswiftui

Swift UI left edge swipe gesture navigate back to previous view not working


I have a simple messaging app and I am trying to implement a left edge swipe gesture to the right in order to navigate out of the ChatView and back to the MessagesHomeView. The problem I'm running into is picking up these gestures over the scroll view. Since the chat view is one big scroll view except for a top header I have to detect edge swipes from the scroll view as well.

When I add the .gesture block to the overall view, only drags on the top header are picked up and the code is executed correctly. But edge drags are not detected from the scroll view portion. Therefore I tried adding the .gesture block to the scroll view but when I try this the screen freezes and the app stops working.

How can I detecte these edge drags off the scroll view?

import SwiftUI

struct ChatView: View {
    @State private var offset = CGSize.zero
    var body: some View {
        VStack {
            
            VStack{
                Text("header")
            }.frame(height: 80)
            
            ScrollView {
                LazyVStack{
                   
                }
            }.gesture (
                DragGesture()
                    .onChanged { gesture in
                        if gesture.startLocation.x < CGFloat(40.0){
                            if gesture.translation.width > 0 {
                                offset = gesture.translation
                                if offset.width > 200.0 {
                                    leaveView()
                                }
                            }
                        }
                    }.onEnded { _ in
                        withAnimation{
                            offset = CGSize.zero
                        }
                    }

            )
        }
        .offset(x: offset.width)
    }
}

Solution

  • This is how you can swipe back to your MessagesHomeView with a NavigationStack

    struct MessagesHomeView: View {
        
       var body: some View {
           NavigationStack {
               VStack {
                   Spacer()
                   NavigationLink(destination: ChatView()) {
                       Text("Navigate to Chat")
                   }
                   Spacer()
               }
           }
       }
    }
    
    
    struct ChatView: View {
        
       var body: some View {
           VStack {
               
               VStack{
                   Text("Chats")
               }
               .frame(height: 80)
               
               ScrollView {
                   LazyVStack{
                      
                   }
               }
           }
       }
    }