带有ScrollView和导航栏SwiftUI的屏幕背景色 [英] Screen Background Color With ScrollView And Navigation Bar SwiftUI
问题描述
我试图在SwiftUI中使用滚动视图时使用彩色背景,但这会导致导航标题不再折叠。我尝试了多种方法,但这始终是一个问题。
Im trying to have a colored background while using a scrollview with SwiftUI but this causes the navigation title to no longer collapse. I've tried a number of ways yet this is always an issue.
struct Person : Identifiable{
var id : Int
var name : String
}
struct ContentView: View {
let people = [
Person(id: 1, name: "Ricky"),
Person(id: 2, name: "Dani"),
Person(id: 3, name: "Mark"),
Person(id: 4, name: "Kailin"),
Person(id: 5, name: "James"),
Person(id: 5, name: "Jenna")
]
var body: some View {
NavigationView{
ZStack{
Color.red
.edgesIgnoringSafeArea(.all)
ScrollView{
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}.navigationBarTitle("Home")
}
}
}
// init(){
// UIView.appearance().backgroundColor = .orange
// }
}
推荐答案
重新排列您的视图,例如:
Rearrange your views like this:
var body: some View {
NavigationView {
ScrollView {
ZStack {
Color.red
VStack {
ForEach(people, id: \.id) { person in
Text(person.name)
.frame(width: 300, height: 400)
.background(Color.blue)
.padding()
}
}
}
}.navigationBarTitle("Home")
}
注意,您可以使用 UINavigatio nBar.appearance()。backgroundColor = .red
以及另一个 UIColor
如 Color(UIColor.red)
为背景,以模拟透明的 NavigationBar
,直到在SwiftUI中更改正确颜色的直接API到达为止。
NOTE THAT You can use UINavigationBar.appearance().backgroundColor = .red
alongside with another UIColor
like Color(UIColor.red)
for the background to simulate the transparent large NavigationBar
until the direct API for changing the proper colors in SwiftUI arrives.
并且注意 UIColor.red
与 Color.red
略有不同。
还注意,如果您想使用列表
而不是 ScrollView
,则应将 .listRowInsets(EdgeInsets())
添加到 ZStack
摆脱多余的空白。
Also NOTE THAT if you want to use a List
instead of ScrollView
, you should add .listRowInsets(EdgeInsets())
to ZStack
to get rid of the extra white space.
这篇关于带有ScrollView和导航栏SwiftUI的屏幕背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!