Dynamic toolbar items in SwiftUI

Viewed 114

How can we dynamically change the items of .toolbar modifier in SwiftUI?

I want to achieve something like the below, but it doesn't compile.

@State private var flag = false

var body: some View {
  //
  // some view code here
  //
  .toolbar {
    if flag {
      ToolbarItemGroup(placement: .principal) {
        Text("Something full width")
          .frame(maxWidth: .infinity, maxHeight: .infinity)
      }
    } else {
      ToolbarItemGroup(placement: .navigationBarTrailing) {
        Button("Something else") { ... }
      }
    }
  }
}
2 Answers

Put condition inside group, like

  .toolbar {
      ToolbarItemGroup(placement: .principal) {
        if flag {
          Button("Something") { ... }
        }
      }
      ToolbarItemGroup(placement: .navigationBarTrailing) {
       if !flag {
         Button("Something else") { ... }
       }
     }
  }

I could achieve it by combining .principal placement and HStack within it. In case you have any better ideas, that's really welcome and appreciated.

.toolbar {
  ToolbarItem(placement: .principal) {
    HStack {
      if flag {
        SearchBar(searchText: $searchText)
          .frame(maxWidth: .infinity, maxHeight: .infinity)

        Button("Cancel") { flag = false }
      } else {
        Spacer()

        Button {
          flag = true
        } label: {
          Image(systemName: "text.magnifyingglass")
        }

        Button {
        } label: {
          Image(systemName: "phone.connection")
        }

        Button {
        } label: {
          Image(systemName: "line.3.horizontal")
        }
      }
    }
  }
}

When the flag is false
enter image description here

and then true
enter image description here

Related