I have placed a linear gradient area at the top of a scrollview as below:
struct ExperimentView: View {
var body: some View {
NavigationStack {
ScrollView {
VStack {
LinearGradient(
colors: [
.blue.opacity(0.5),
.clear
],
startPoint: .top,
endPoint: .bottom
)
.frame(height: 200)
Text("Element")
Text("Element")
Text("Element")
}
}
.ignoresSafeArea(.all)
}
}
}
The problem is, the scroll view can be pulled downward and reveal the background color above the top edge.
So is there a way to extend the blue color upward beyond the top edge, so when pulled downward, it still looks continuing upward?
I tried to add a solid color above the gradient header, and set and offset to the VStack inside the scrollview:
struct ExperimentView: View {
let height = UIScreen.main.bounds.height
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing:0) {
Color.blue.opacity(0.5)
.frame(height: height)
LinearGradient(
colors: [
.blue.opacity(0.5),
.clear
],
startPoint: .top,
endPoint: .bottom
)
.frame(height: 200)
Text("Element")
Text("Element")
Text("Element")
}
.offset(y: -height)
}
.ignoresSafeArea(.all)
}
}
}
While it seems to work with pulling down, the offset would leave a space with the height of the screen at the bottom of the scrollable area, leaving a full blank page when scrolling up, rather than bouncing back when reaching the last element inside the scrollview.
So is there a better way to solve this?
You could move the gradient to the background of the
ScrollViewinstead:EDIT As you point out in your comment, this makes the gradient fixed. If you want it to move with the
VStackthen I would suggest moving it to the background of theVStackinstead. Also:VStackor to the first text element, to move the text down below the gradient (if required).Alternatively, to build the
VStackin the same way as before, the gradient could be moved to the background of a placeholder that is the first item in theVStack: