如何在 SwiftUI 中更改视图

Div*_*Div 1 swift swiftui

使用后如何修改视图?例如:

var body: some View {
    Button (action: {
        // Code to move button's position. self.offset(x:y:) doesn't work, Xcode says 'result of call to offset is unused'
    }) {
        Text("How to I alter the colour of this text?") // Change colour somewhere else in my script
            .background(Color.black)

    }
        .frame(alignment: .leading)

}
Run Code Online (Sandbox Code Playgroud)

我需要在实例化后修改视图。因为一切都是一个视图,从.frame.background,我不应该需要引用/删除/修改/将它们添加到堆栈中吗?

Mat*_*ini 7

颜色的变化是状态的变化。

您可以使用属性包装器@State,它是 SwiftUI 的一部分。

在 WWDC 2019 的精彩演讲中详细介绍了这一点:

SwiftUI 简介:构建您的第一个应用程序

struct ContentView: View {

    @State var someState: Bool = true

    var body: some View {
        Button (action: {
            // The state is toggled, and a redraw is triggered
            self.someState.toggle()
        }) {
        Text("How do I alter the colour of this text?")
            // Set color according to the state
            .foregroundColor(someState ? Color.black : Color.pink)
        }
        .frame(alignment: .leading)
    }

}
Run Code Online (Sandbox Code Playgroud)

当发生变化@State时,视图body被重绘。