-1

Good morning, everyone,

I am learning SwiftUI, and I watched the whole course on Raywenderlich's website ("Your First Ios and SwiftUI app").

In it, we learn to create a struct and method that allows us to modify a view.

While trying to create a small application, thanks to this answer, I know that I have to create a ZStack to be able to modify the background.

However, when I try to create a struct and method to modify my ZStack, many errors are reported.

Here's my code :

public struct BackGroundColor : ModifiedContent {
    public body (content : Content) -> some View {
        return content
        Color.init(red: 222/255, green: 196/255, blue: 125/255)
            .edgesIgnoringSafeArea(.all)
    }
}

// When I call the struc in my body 

struct ContentView: View {

    var body: some View {

        ZStack {
            .BackGroundColor()
       // some code
        }

    }
}

In addition, I would like this struct to be public so that it can be used anywhere in my other files.

Thank you for your answers ‍

Lucas A.
  • 1
  • 1

1 Answers1

0

There are at least three ways that you could accomplish what you want. All of them take your view and wrap it in the ZStack, on top of a Color view. The main difference is in how they are called.

1. Using a View

public struct BackgroundColorView<Content: View>: View {
    var view: Content

    var body: some View {
        ZStack {
            Color(red: 222/255, green: 196/255, blue: 125/255)
                .edgesIgnoringSafeArea(.all)
            view
        }
    }
}

And you call it like this:

BackgroundColorView(view: Text("Hello World"))

2. Using a ViewModifier

public struct BackgroundColorModifier: ViewModifier {
    func body(content: Content) -> some View {
        ZStack {
            Color(red: 222/255, green: 196/255, blue: 125/255)
                .edgesIgnoringSafeArea(.all)
            content
        }
    }
}

And you call it like this:

Text("Hello World")
        .modifier(BackgroundColorModifier())

3. Using a View extension

extension View {
    public func colorBackground() -> some View {
        ZStack {
            Color(red: 222/255, green: 196/255, blue: 125/255)
                .edgesIgnoringSafeArea(.all)
            self
        }
    }
}

And you call it like this:

Text("Hello World")
    .colorBackground()

Which to use?

I personally find #3 to be the nicest option, and it is easily extended to take a color parameter:

extension View {
    public func colorBackground(_ color: Color) -> some View {
        ZStack {
            color
                .edgesIgnoringSafeArea(.all)
            self
        }
    }
}

And you call it like this:

Text("Hello World")
    .colorBackground(Color.red)
John M.
  • 8,892
  • 4
  • 31
  • 42