42

SwiftUI Background Color Tutorial

 4 years ago
source link: https://www.tuicool.com/articles/7JzQ3yj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In SwiftUI the background color can be applied to every view. To change the background color to the whole screen a ZStack must be used. In this tutorial a red background color is set using a ZStack .SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project . In the template selector, select iOS as the platform, select the Single View App template, and then click Next . Enter SwiftUIBackgroundColorTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next . Choose a location to save the project on your Mac.

u2iEJjQ.png!web

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

QF3Ibe3.png!web

In the Project navigator, click to select ContentView.swift . Change the code inside the ContentView struct to

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.red
        }
    }
}

ZStack is a stack type for creating overlapping content. The red color is set inside the ZStack

The preview will look like this.

UbiA3qJ.png!web

The background color is applied to the safe area. To change the color background outside the safe area the .edgesIgnoringSafeArea() modifier must be used.

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

Now the preview updates the background color outside the safe area.

reuQR3Y.png!web

The source code of the SwiftUIBackgroundColorTutorial can be downloaded at the ioscreator repository on Github .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK