I am writing a SwiftUI app where I need to have different texts inside the large and compact navigationBar title.
My approach was to observe the change in alpha values of the toolbar using Swift-Introspect as shown below but that met no luck.
I tried to achieve this by trying to attach a ViewController to my ContentView
with no luck as in here: Is it possible to assign a ViewController to a SwiftUI view?
struct ContentView: View {
@State private var titleString: String = ""
@State private var observer: NSKeyValueObservation?
var body: some View {
ZStack {
NavigationView {
ScrollView {
VStack (alignment: .leading) {
Text("Some Random Text Again")
}.frame(maxWidth: .infinity, alignment: .topLeading)
.padding().padding(.leading)
}.navigationTitle("Large Title")
.toolbar {
ToolbarItem(placement: .principal) {
Text(titleString)
}
}
.introspectNavigationController {nav in
let toolbarView = nav.toolbar
self.observer = toolbarView?.observe(\.alpha, options: [.new], changeHandler: { (toolbar, changes) in
if toolbar.alpha == 1 {
self.titleString = "Inline Text"
} else {
self.titleString = "Toolbar is Hidden"
}
})
}
}
}
}
}
The process above seems to not be working. Is there any better way to observe the change in the alpha value of the toolbar?