使用修改器自定义背景

时间:2019-11-01 23:58:47

标签: swift xcode swiftui

大家早上好

我正在学习SwiftUI,并且在Raywenderlich的网站(“您的第一个Ios和SwiftUI应用”)上观看了整个课程。

在其中,我们学习创建允许我们修改视图的结构和方法。

在尝试创建小型应用程序时,由于有了answer,我知道我必须创建一个ZStack才能修改背景。

但是,当我尝试创建结构和方法来修改ZStack时,会报告许多错误。

这是我的代码:

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
        }

    }
}

此外,我希望此结构是公共的,以便可以在我的其他文件中的任何位置使用它。

谢谢您的回答?

1 个答案:

答案 0 :(得分:0)

您至少可以通过三种方法来完成所需的工作。它们全都采用您的视图,并将其包装在Color视图顶部的ZStack中。主要区别在于它们的调用方式。

1。使用视图

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

您这样称呼它:

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

2。使用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
        }
    }
}

您这样称呼它:

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

3。使用View扩展程序

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

您这样称呼它:

Text("Hello World")
    .colorBackground()

使用哪个?

我个人认为#3是最好的选择,并且很容易扩展为采用颜色参数:

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

您这样称呼它:

Text("Hello World")
    .colorBackground(Color.red)