简体   繁体   English

在 SwiftUI 中更改 UIView 背景颜色

[英]Change UIView background color in SwiftUI

Hello everyone.大家好。 I'm creating a simple iOS app with SwiftUI, and I'd like to change my view's background color to a custom one I have.我正在使用 SwiftUI 创建一个简单的 iOS 应用程序,我想将视图的背景颜色更改为我拥有的自定义背景颜色。

This is something extremely easy to do but it seems that it's impossible to achieve in SwiftUI without using ZStacks or workarounds like that, which if you use a List, for example, don't work.这是一件非常容易做到的事情,但如果不使用 ZStacks 或类似的解决方法,似乎在 SwiftUI 中是不可能实现的,例如,如果您使用列表,则不起作用。

I want to change the color of the view, not use a ZStack with a custom color and then put the rest of the views on top of it.我想更改视图的颜色,而不是使用带有自定义颜色的 ZStack,然后将其余的视图放在它上面。 I tried using UIView.appearance().backgroundColor = color when initializing my view, but then all the view is hidden and the screen is filled with the color chosen.我在初始化我的视图时尝试使用UIView.appearance().backgroundColor = color ,但随后所有视图都被隐藏并且屏幕被选择的颜色填充。

As I'm not good at explaining, here you have some images describing the problem:由于我不擅长解释,这里有一些描述问题的图像:

Without color change无颜色变化无颜色变化

With color change随着颜色变化随着颜色变化

My code我的代码

import SwiftUI

struct TabController: View {
    @State private var selection = 0

    init() {
        UIView.appearance().backgroundColor = UIColor(named: "backgroundColor")
    }

    var body: some View {
        TabView(selection: $selection) {
            HomePageView()
                .tabItem {
                    Image(systemName: "house.fill")
                        .font(.title)
                }
                .tag(0)

            Text("Second View")
                .font(.title)
                .tabItem {
                    Image(systemName: "bell.fill")
                        .font(.title)
                }
                .tag(1)
        }.edgesIgnoringSafeArea(.top)
    }
}

Hope this will help to understand:希望这有助于理解:

var body: some View {
    Color.purple
        .overlay(
            VStack(spacing: 20) {
                Text("Overlay").font(.largeTitle)
                Text("Example").font(.title).foregroundColor(.white)
        })
        .edgesIgnoringSafeArea(.vertical)
}

Another If you use the views in Group另一个如果您使用 Group 中的视图

var body: some View {
        Group {
          Text("Hello SwiftUI!")
        }
       .background(Color.black)
    }

For changing the background color, I think the current method most people, and myself, are using is using a ZStack.对于更改背景颜色,我认为大多数人和我自己目前使用的方法使用 ZStack。 I haven't seen many problems with putting a UIViewRepresentable on top of it.我没有看到将 UIViewRepresentable 放在它上面的很多问题。

var body: some View {
    ZStack {
        Color.blue
            .edgesIgnoringSafeArea(.all)
        VStack {
          Text("Hello World!")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM