如何在SwiftUI的NavigationView中设置ScrollView的背景色 [英] How to set ScrollView's background color in NavigationView in SwiftUI
问题描述
我无法在SwiftUI的 ScrollView
下设置背景色.当我使用 .background(Color.red)
时,背景被切断,因此它不会进入导航栏,并且滚动似乎被破坏了.我尝试了几种解决方案,但是每种解决方案都行不通.我有一个简单的视图层次结构
I can't set a background color under ScrollView
in SwiftUI. When I use .background(Color.red)
the background is cut off so it doesn't go under navigation bar and scrolling seems to be broken.
I tried a couple of solutions but each of them doesn't work.
I have a simple view hierarchy
NavigationView {
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
.navigationViewStyle(StackNavigationViewStyle())
它按预期工作
现在,我想添加背景色,我尝试了以下解决方案
now, I would like to add a background color, I tried the following solutions
NavigationView {
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.background(Color.red)
.navigationBarTitle("Title", displayMode: .large)
}
.navigationViewStyle(StackNavigationViewStyle())
结果
NavigationView {
ZStack {
Color.red
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
}
.navigationViewStyle(StackNavigationViewStyle())
结果
NavigationView {
ZStack {
Color.red.edgesIgnoringSafeArea([.all])
ScrollView([.vertical], showsIndicators: true) {
VStack {
ForEach(0...50, id: \.self) { _ in
Text("Text text")
}
}
}
.navigationBarTitle("Title", displayMode: .large)
}
}
.navigationViewStyle(StackNavigationViewStyle())
结果
如何在 NavigationView
中的 ScrollView
下设置背景颜色?
How to set up a background color under ScrollView
packed in NavigationView
?
//
下面的动画呈现出理想的效果(由UIKit制作).
The animation below presents a desirable effect (it is made with UIKit).
推荐答案
在排除了所有可能性之后,我使用了以下解决方案,该解决方案非常适合您想要实现的目标.
After exhausting all possibilities, I landed with the below solution which works perfectly for what you want to achieve.
struct DemoView: View {
init(){
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.backgroundColor = UIColor.red
UIScrollView.appearance().backgroundColor = UIColor.red
}
var body: some View {
NavigationView{
ScrollView{
VStack{
ForEach(0..<30, id: \.self){ _ in
Text("Text Text").foregroundColor(Color.black)
}
}.frame(maxWidth: .infinity)
.background(Color(UIColor.red))
}.navigationBarTitle("Title")
}
}
}
希望这会有所帮助;)
这篇关于如何在SwiftUI的NavigationView中设置ScrollView的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!