代码之家  ›  专栏  ›  技术社区  ›  NotAgent48

Swift UI-我正在尝试更改背景。它在功能按钮pressed()下给了我一个错误

  •  0
  • NotAgent48  · 技术社区  · 2 年前

    这是一个我正在进行的项目,基本上可以让我有一个欢迎页面。单击“单击此处”后,按下的按钮应使用新颜色填充新背景(创建新场景)。。。我希望以后能补充更多。

    import SwiftUI
    
    struct ContentView: View {
        
        // defined global variables in a function
        @State var backgroundColor: Color = Color.red
        
        var body: some View {
            ZStack {
                // background called
                backgroundColor
                    .edgesIgnoringSafeArea(.all)
    
                // content
                contentLayer
                }
            }
    
        var contentLayer: some View {
                // content
            VStack {
                Text("Welcome to newsapptest!")
                    .font(.largeTitle)
                    
                    Button(action: {
                        buttonPressed()
                    }, label: {
                        Text("Click here to continue to the app!")
                            .font(.headline)
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.black)
                            .cornerRadius(10)
                    })
                }
            }
        }
        
        func buttonPressed() {
            backgroundColor = .blue
    

    背景颜色=。blue给了我一个问题,说它不在我的范围内。我怎样才能解决这个问题?

    }

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   jnpdx    2 年前

    如果格式化代码(选择并使用 ctrl-i ),您将看到 buttonPressed 函数实际上是 外部 您的 ContentView 结构。将其移到内部,它将正确编译:

    struct ContentView: View {
        
        // defined global variables in a function
        @State var backgroundColor: Color = Color.red
        
        var body: some View {
            ZStack {
                // background called
                backgroundColor
                    .edgesIgnoringSafeArea(.all)
                
                // content
                contentLayer
            }
        }
        
        var contentLayer: some View {
            // content
            VStack {
                Text("Welcome to newsapptest!")
                    .font(.largeTitle)
                
                Button(action: {
                    buttonPressed()
                }, label: {
                    Text("Click here to continue to the app!")
                        .font(.headline)
                        .foregroundColor(.white)
                        .padding()
                        .background(Color.black)
                        .cornerRadius(10)
                })
            }
        }
        
        func buttonPressed() {
            backgroundColor = .blue
        }
    }