如何在其onAppear闭包中访问VStack?

huangapple go评论63阅读模式
英文:

How to access VStack from within its onAppear closure?

问题

如何在其自己的onAppear闭包中访问VStack?我尝试将堆栈作为ContentView的实例属性,但了解到VStack不是一种类型,而是一种类型构造器。我的选择有哪些,最佳实践是什么?

struct ContentView: View {
    var body: some View {
        VStack {
            
        }
        .background(.red)
        .onAppear {
            // 将VStack的背景颜色更改为蓝色
        }
    }
}
英文:

How do I access the VStack from within its own onAppear closure? I tried making the stack an instance property of ContentView but learned that VStack is not a type, but a type constructor. What are my options and what is best practice?

struct ContentView: View {
    var body: some View {
        VStack {
            
        }
        .background(.red)
        .onAppear {
            // change VStack background color to blue
        }
    }
}

答案1

得分: 1

你无法访问VStack的内部,但可以创建变量,VStackonAppear都可以访问。

struct ContentView: View {
    @State private var vStackBackground: Color = .red
    var body: some View {
        VStack {
            Text("测试")
        }
        .background(vStackBackground)
        .onAppear {
            self.vStackBackground = .blue
        }
    }
}
英文:

You can't access the VStack internals but you can create a variables that both the VStack and the onAppear can access.

struct ContentView: View {
    @State private var vStackBackground: Color = .red
    var body: some View {
        VStack {
            Text("Test")
        }
        .background(vStackBackground)
        .onAppear {
            self.vStackBackground = .blue
        }
    }
}

huangapple
  • 本文由 发表于 2023年5月25日 02:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76326611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定