【问题标题】:Customize a background with a Modifier使用修改器自定义背景
【发布时间】:2020-02-28 05:11:50
【问题描述】:

大家早上好,

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

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

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

    }
}

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

感谢您的回答 ??????‍????

【问题讨论】:

    标签: swift xcode swiftui


    【解决方案1】:

    至少有三种方法可以实现你想要的。所有这些都将您的视图包裹在 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)
    

    【讨论】:

    • 感谢您的详细解答,不胜感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    相关资源
    最近更新 更多