在SwiftUI中更改UIView背景颜色

时间:2019-09-06 16:32:24

标签: ios swift swiftui

大家好。我正在使用SwiftUI创建一个简单的iOS应用,我想将视图的背景颜色更改为我拥有的自定义颜色。

这是一件非常容易做到的事,但是如果不使用ZStacks或类似的变通方法,在SwiftUI中似乎是不可能实现的,例如,如果您使用List则无法使用。

我要更改视图的颜色,而不是使用具有自定义颜色的ZStack,然后将其余视图放在其顶部。我在初始化视图时尝试使用UIView.appearance().backgroundColor = color,但随后所有视图都被隐藏,屏幕上充满了所选的颜色。

由于我不擅长解释,因此这里有一些描述问题的图片:

颜色不变 Without color change

具有颜色更改 With color change

我的代码

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)
    }
}

2 个答案:

答案 0 :(得分:1)

希望这将有助于您了解:

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

另一个,如果您使用“组”中的视图

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

答案 1 :(得分:0)

为了改变背景颜色,我认为目前大多数人和我自己使用的方法使用 ZStack。我没有看到将 UIViewRepresentable 放在它上面的很多问题。

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