Swiftui searchable Cancel button

493 Views Asked by At

I have a NavigationView with .searchable, when clicking Cancel I want to go to the previous View like Back button. İ use @Environment(\.isSearching), it is running, I can print Searching canceled but how to navigate to the previous View ?

2

There are 2 best solutions below

0
Timmy On

You can simply listen to the changes made to isSearching, and pop your view using @Environment(\.presentationMode):

.onChange(of: isSearching) { newValue in
    guard !newValue else {return}
    presentationMode.wrappedValue.dismiss()
    //for iOS 16 +, use dismiss.callAsFunction()
}

Note: presentationMode is first deprecated in iOS 15+, so for newer versions use @Environment(\.dismiss).

0
Raul Pascual On

If you are using iOS 13+, you can use @Environment(\.dismiss) var dismiss And then use dismiss() in the action