如何在 swiftUI 中为 viewController 设置背景颜色? [英] How to set a background color for the viewController in swiftUI?

查看:47
本文介绍了如何在 swiftUI 中为 viewController 设置背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在 swiftUI 中为整个 viewController 设置背景颜色,但我无法做到.该视图不采用属性 .backgroundColor .

I have been trying to set a background color for the whole viewController in swiftUI but I habe not able to. The view does no take the attribute .backgroundColor .

我也尝试在 sceneDelegate 中为 viewController 使用 .backgroundColor 属性,但它没有采用该属性,但采用了 foregroundColor 属性.

I have tried using the .backgroundColor attribute for the viewController in sceneDelegate too and it is not taking the attribute but it takes the foregroundColor attribute.

推荐答案

到目前为止,我发现最有效的方法是在 ContentView 主体的顶部创建一个 ZStack 并为第一层设置一个 Color,它忽略了安全区.Apple 将 Color 定义为后期绑定令牌",无论它是什么,但它的行为与任何其他 View 相似.

So far, what I have found to work best is to create a ZStack at the top of the ContentView body and have the first layer a Color, that ignores the safe area. Apple defines a Color as "a late-binding token", whatever that is, but it behaves similar to any other View.

struct ContentView: View {
  var body: some View {
    ZStack {
      Color.red
      .edgesIgnoringSafeArea(.all)

      /// Your Inner View content goes here.
      VStack {
        Text("Hello") 
      } // VStack

    } // ZStack
  } // body View
}  // ContentView

注意:注意内部视图中的内容,因为它很容易扩展以填充整个窗口,从而将背景颜色覆盖为白色等.例如,流行的 NavigationView 倾向于扩展到整个窗口,对我来说,它往往会忽略其记录的 .background() 设置.您也可以在这里执行相同的 ZStack 策略.

Note: Be careful about what is inside the Inner View because it can easily expand to fill the entire window thus overlaying your background color with white, etc. For example, the popular NavigationView tends to expand to the entire window and for me it tends to ignore its documented .background() setting. You can do the same ZStack strategy here too.

NavigationView {
  ZStack { 
    Color.red.edgesIgnoringSafeArea(.all) 
    VStack {
      Text("Hello")
    } // VStack
  } // ZStack
}  // NavigationView

这篇关于如何在 swiftUI 中为 viewController 设置背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆