Search code examples
iosswiftuiswiftui-navigationlinkswiftui-navigationview

iOS SwiftUI - NavigationView NavigationLink: Close view with custom Button


I'm new to iOS development and think it's awesome, BUT I absolutely H A T E everything about NavigationView/NavigationLink, even in Android it's very hard to find such idiocy!

In ContentView I have:

NavigationLink(destination: Login().navigationBarBackButtonHidden(true), label: {
    Image(systemName: "person.circle.fill")
        .resizable()
        .aspectRatio(contentMode: .fit).frame(width: 32)
        .foregroundColor(Color(UIColor(named: "IconColor")!))
})

And Login():

struct Login: View {
    @AppStorage("userid") var userid: Int = 0

    var body: some View{
        
        VStack{
            
            HStack{
                
                Spacer()
                
                Button(action: {
                    // Close the view!!???
 
                }) {
                    Image(systemName: "xmark")
                        .resizable()
                        
                        .frame(width: 18, height: 18)
                        .foregroundColor(Color(UIColor(named: "IconColor")!))
                }
                .padding(.top, 12.0)
                .padding(.trailing, 16.0)
            }
                         
            Spacer()
            
        }
        
    }
}

How can I just close the View clicking on the button?


Solution

  • You would use presentationMode.wrappedValue.dismiss(). Take a look at this for more information. Here is how you would use it:

    struct Login: View {
        @AppStorage("userid") var userid: Int = 0
    //Doesn't require anything to be passed in.
      @Environment(\.presentationMode) var presentationMode
        var body: some View{
            
            VStack{
                
                HStack{
                    
                    Spacer()
                    
                    Button(action: {
    //Part where view is dismissed
                       presentationMode.wrappedValue.dismiss()
     
                    }) {
                        Image(systemName: "xmark")
                            .resizable()
                            
                            .frame(width: 18, height: 18)
                            .foregroundColor(Color(UIColor(named: "IconColor")!))
                    }
                    .padding(.top, 12.0)
                    .padding(.trailing, 16.0)
                }
                             
                Spacer()
                
            }
            
        }
    }
    

    You would still call this the same way, with a NavigationLink like in the original question above.

    Take a look at this answer for more info on dismissing. Also, note that this will disable the default swipe-back behavior, if you want to re-enable it, take a look here.