首页 > 解决方案 > 使用修改器自定义背景

问题描述

大家,早安,

我正在学习 SwiftUI,我在 Raywenderlich 的网站上观看了整个课程(“Your First Ios and SwiftUI app”)。

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

在尝试创建一个小型应用程序时,感谢这个答案,我知道我必须创建一个 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
        }

    }
}

此外,我希望这个结构是公开的,以便它可以在我的其他文件中的任何地方使用。

谢谢你的回答‍</p>

标签: swiftxcodeswiftui

解决方案


至少有三种方法可以实现你想要的。所有这些都获取您的视图并将其包装在 ZStack 中,位于 Color 视图之上。主要区别在于它们的调用方式。

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.使用视图扩展

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)

推荐阅读