scrollview粘贴
Quick SwiftUI tip for today. If you don’t like that annoying white space a user sees when they scroll past the top of your ScrollView
, a Sticky Header works perfectly!
今天的SwiftUI快速提示。 如果您不喜欢当用户滚动到ScrollView
顶部时看到的烦人的空白,那么粘性页眉会完美地工作!
Before getting started, please consider subscribing using this link, and if you aren’t reading this on TrailingClosure.com, please come check us out sometime!
在开始之前,请考虑使用此链接进行订阅,如果您未在TrailingClosure.com上阅读此链接 ,请随时联系我们!
Place this StickyHeader
component at the top of a ScrollView
and any content you put inside will stretch in size to fill that gap when a user scrolls to the top. See the video below for an example!
将这个StickyHeader
组件放置在ScrollView
的顶部,当用户滚动到顶部时,您放入其中的任何内容都会扩大大小以填补该空白。 请参见下面的视频作为示例!
struct StickyHeader<Content: View>: View {
var minHeight: CGFloat
var content: Content
init(minHeight: CGFloat = 200, @ViewBuilder content: () -> Content) {
self.minHeight = minHeight
self.content = content()
}
var body: some View {
GeometryReader { geo in
if(geo.frame(in: .global).minY <= 0) {
content
.frame(width: geo.size.width, height: geo.size.height, alignment: .center)
} else {
content
.offset(y: -geo.frame(in: .global).minY)
.frame(width: geo.size.width, height: geo.size.height + geo.frame(in: .global).minY)
}
}.frame(minHeight: minHeight)
}
}
如何使用 (How To Use)
Here are some quick examples of how you can use it in your next project.
这里有一些快速的示例,说明如何在下一个项目中使用它。
粘性标题标题/说明 (Sticky Header Title / Description)
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
StickyHeader {
ZStack {
Color(red: 35/255, green: 45/255, blue: 50/255)
VStack {
Text("Joshua Tree")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.white)
Text("California")
.font(.title2)
.fontWeight(.semibold)
.foregroundColor(.white)
}
}
}
// Scroll View Content Here
// ...
}
}
粘性标题图片 (Sticky Header Image)
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
StickyHeader {
StickyHeader {
Image("cover")
.resizable()
.aspectRatio(contentMode: .fill)
}
}
// Scroll View Content Here
// ...
}
}
翻译自: https://levelup.gitconnected.com/scrollview-sticky-header-462b9300378e
scrollview粘贴