[英]Show NavigationBar when scrolling down
I have this simple code with a hidden NavigationBar but what I want is to show it when scrolling down.我有一个带有隐藏 NavigationBar 的简单代码,但我想要的是在向下滚动时显示它。 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
.现在
.navigationBarHidden(barHidden)
是可动画的,并且具有旧的NavigationView
和新的NavigationStack
。
struct ContentView: View {
@State private var barHidden = true
var body: some View {
NavigationStack { // << Tested !!
ScrollView(showsIndicators: false) {
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用 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()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.