I have this simple code with a hidden NavigationBar but what I want is to show it when scrolling down. How can I do that?
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView(showsIndicators: false) {
VStack {
ForEach(0 ..< 3) { _ in
Image(systemName: "rectangle.fill")
.resizable()
.aspectRatio(contentMode: .fill)
.padding()
}
}
}
.navigationBarTitle("Title Here", displayMode: .inline)
.navigationBarHidden(true)
}.edgesIgnoringSafeArea(.all)
}
}
Now .navigationBarHidden(barHidden)
is animatable, and with old NavigationView
and with new NavigationStack
.
struct ContentView: View {
@State private var barHidden = true
var body: some View {
NavigationStack { // << Tested !!
ScrollView(showsIndicators: false) {
Test module is here
It is possible but this modifier is not animatable, so bar appears instantly (the same is observed when toggle bar with button). Anyway I think it worth posting.
Tested with Xcode 12 / iOS 14
struct ContentView: View {
@State private var barHidden = true
var body: some View {
NavigationView {
ScrollView(showsIndicators: false) {
VStack {
ForEach(0 ..< 3) { _ in
Image(systemName: "rectangle.fill")
.resizable()
.aspectRatio(contentMode: .fill)
.padding()
}
}.background(GeometryReader {
Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) {
if !barHidden && $0 < 50 {
barHidden = true
print("<< hiding")
} else if barHidden && $0 > 50{
barHidden = false
print(">> showing")
}
}
}.coordinateSpace(name: "scroll")
.navigationBarTitle("Title Here", displayMode: .inline)
.navigationBarHidden(barHidden)
}
.animation(.default, value: barHidden)
.edgesIgnoringSafeArea(.all)
}
}
struct ViewOffsetKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value += nextValue()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With