简体   繁体   中英

iOS SwiftUI - NavigationView NavigationLink: Close view with custom Button

I'm new to iOS development and think it's awesome, BUT I absolutely HATE 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM