我正在尝试更改此 View 的主要背景颜色,但无法执行。我试图将背景(Color.green)放在 HStack、VSTack 甚至 ZStack 上,但它没有用,不确定我是否放在正确的位置。默认情况下,它采用白色的手机或模拟器颜色,但我想应用自定义背景颜色 我的 Xcode 版本是 11.5
struct HomePageView: View {
@State var size = UIScreen.main.bounds.width / 1.6
var body: some View {
GeometryReader{_ in
VStack {
HStack {
ZStack{
// main home page components here....
NavigationView{
VStack {
AssignmentDaysView()
}.background(Color.lairBackgroundGray)
.frame(width: 100, height: 100, alignment: .top)
.navigationBarItems(leading: Button(action: {
self.size = 10
}, label: {
Image("menu")
.resizable()
.frame(width: 30, height: 30)
}).foregroundColor(.appHeadingColor), trailing:
Button(action: {
print("profile is pressed")
}) {
HStack {
NavigationLink(destination: ProfileView()) {
LinearGradient.lairHorizontalDark
.frame(width: 30, height: 30)
.mask(
Image(systemName: "person.crop.circle")
.resizable()
.scaledToFit()
)
}
}
}
).navigationBarTitle("Home", displayMode: .inline)
}
HStack{
menu(size: self.$size)
.cornerRadius(20)
.padding(.leading, -self.size)
.offset(x: -self.size)
Spacer()
}
Spacer()
}.animation(.spring()).background(Color.lairBackgroundGray)
Spacer()
}
}
}
}
}
struct HomePageView_Previews: PreviewProvider {
static var previews: some View {
HomePageView()
}
}
最佳答案
在您的 NavigationView
中,您有一个 VStack
。相反,您可以使用 ZStack
并在 VStack
下方添加背景。
尝试以下操作:
NavigationView {
ZStack {
Color.green // <- or any other Color/Gradient/View you want
.edgesIgnoringSafeArea(.all) // <- optionally, if you want to cover the whole screen
VStack {
Text("assignments")
}
.background(Color.gray)
.frame(width: 100, height: 100, alignment: .top)
}
}
注意:您使用了许多包装在您不使用的 GeometryReader
中的堆栈。考虑通过删除不必要的堆栈来简化 View 。此外,如果您使用 UIScreen.main.bounds
,您可能不需要 GeometryReader(但是,GeometryReader
在 SwiftUI 中是首选)。
尝试移除一些层:您可以从移除最上面的层开始:GeometryReader
、VStack
、HStack
...
关于ios - 无法在 SwiftUI 中更改 View 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715050/