Home > database >  How to bring up a separate view when a search bar is clicked? [SwfitUI]
How to bring up a separate view when a search bar is clicked? [SwfitUI]

Time:11-03

I'm trying to implement a search bar that brings up a separate view (see Twitter example).

Gif showing twitter search bar animation

How is this implemented? My initial thought was to somehow use a NavigationView to wrap around the search bar view, and when user clicks on the search bar, calls NavigationLink that'd bring up the separate view.

But is this the right way? The Twitter example doesn't seem to display NavigationView elements like the "< Back" button, nor does the animation transition match.

CodePudding user response:

FocusState is a state, but it sets a variable. Therefore, you can key off that change with an .onChange(of:perform:) like this.

struct ContentView: View {
    @FocusState var isFocused: Bool
    ...
    var body: some View {
        TextField("TextField", text: $text)
                .focused($isFocused)
                .onChange(of: isFocused, perform: { newValue in
                    print("focus")
                })
        ...
    }
}

It won't work if you use it on other TextFields, but is will trigger on this.

  • Related