SwiftUI - How do I change the background color of

2020-02-26 13:29发布

I'm beginning to try out SwiftUI and I'm surprised that it doesn't seem to be straightforward to change the background color of a View. How do you do this using SwiftUI?

11条回答
smile是对你的礼貌
2楼-- · 2020-02-26 14:30

You can Simply Change Background Color of a View:

var body : some View{


    VStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}

and You can also use ZStack :

var body : some View{


    ZStack{

        Color.blue.edgesIgnoringSafeArea(.all)

    }


}
查看更多
▲ chillily
3楼-- · 2020-02-26 14:31

Use Below Code for Navigation Bar Color Customization

struct ContentView: View {

@State var msg = "Hello SwiftUI                                                                    
查看更多
叼着烟拽天下
4楼-- · 2020-02-26 14:33

For List:

All SwiftUI's Lists are backed by a UITableViewin iOS. so you need to change the background color of the tableView. But since Color and UIColor values are slightly different, you can get rid of the UIColor.

struct ContentView : View {
    init(){
        UITableView.appearance().backgroundColor = .clear
    }

    var body: some View {
        List {
            Section(header: Text("First Section")) {
                Text("First Cell")
            }
            Section(header: Text("Second Section")) {
                Text("First Cell")
            }
        }
        .background(Color.yellow)
    }
}

Now you can use Any background (including all Colors) you want


Also First look at this result:

View hierarchy

As you can see, you can set the color of each element in the View hierarchy like this:

struct ContentView: View {

    init(){
        UINavigationBar.appearance().backgroundColor = .green 
        //For other NavigationBar changes, look here:(https://stackoverflow.com/a/57509555/5623035)
    }

    var body: some View {
        ZStack {
            Color.yellow
            NavigationView {
                ZStack {
                    Color.blue
                    Text("Some text")
                }
            }.background(Color.red)
        }
    }
}

And the first one is window:

window.backgroundColor = .magenta

The very common issue is we can not remove the background color of SwiftUI's HostingViewController (yet), so we can't see some of the views like navigationView through the views hierarchy. You should wait for the API or try to fake those views (not recommended).

查看更多
神经病院院长
5楼-- · 2020-02-26 14:34

The code on Scene delegate in Swift UI

Content view background-color

window.rootViewController?.view.backgroundColor = .lightGray

查看更多
等我变得足够好
6楼-- · 2020-02-26 14:35

like this

struct ContentView : View {
    @State var fullName: String = "yushuyi"
    var body: some View {        
        VStack
            {
                TextField($fullName).background(SwiftUI.Color.red)
                Spacer()
        }.background(SwiftUI.Color.yellow.edgesIgnoringSafeArea(.all))
    }
}
查看更多
登录 后发表回答