5

Moving a button up into the navigation bar only triggers once when it has a sheet attached. The button is used to show a search window but once the popup is closed the button remains inactive.

The attached code is a simplified version of what I tried. At first I used a button in the main part to activate the search window but I thought that the navigation bar would take less space. The activation worked but in that case I couldn't deactivate it.

import SwiftUI

struct ContentView: View {
    @State var showingSearch: Bool = false

    var body: some View {
        NavigationView {
            VStack {
                Text("Hello World!")
                Button(
                    action: { self.showingSearch = true },
                    label: { Image(systemName: "magnifyingglass") }
                )
                .sheet(
                    isPresented: $showingSearch,
                    content: { Search( showingSearch: self.$showingSearch ) }
                )
            }

            .navigationBarItems(
                leading: Image(systemName: "square.and.pencil"),
                trailing: Button(
                        action: { self.showingSearch = true },
                        label: { Image(systemName: "magnifyingglass") }
                    )
                    .sheet(
                        isPresented: $showingSearch,
                        content: { Search( showingSearch: self.$showingSearch ) }
                    )
            )
        }
    }
}

struct Search: View {
    @Binding var showingSearch: Bool

    var body: some View {
        NavigationView {
            Text("Search")
            .navigationBarTitle("Search", displayMode: .inline)
            .navigationBarItems(trailing:
                Button(
                    action: { self.showingSearch = false },
                    label: {Image(systemName: "clear") }
                )
            )
        }
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

I expect that the two buttons should behave the same. Both magnifying glasses should activate the search window and the clear button should deactivate it ready for a new attempt but it appears that button in the navigation bar isn't seeing the change in showingSearch.

Michael Salmon
  • 1,056
  • 7
  • 15

1 Answers1

2

It's a known bug related to navigation bar items and not relegated to just sheets, it seems to affect any modal, and I've encountered it in IB just the same when using modal segues.

Unfortunately this issue is still present in 11.3 build, hopefully they get this fixed soon.

Trapp
  • 4,349
  • 1
  • 14
  • 12