使用后如何修改视图?例如:
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
,我不应该需要引用/删除/修改/将它们添加到堆栈中吗?
颜色的变化是状态的变化。
您可以使用属性包装器@State
,它是 SwiftUI 的一部分。
在 WWDC 2019 的精彩演讲中详细介绍了这一点:
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
被重绘。
归档时间: |
|
查看次数: |
2672 次 |
最近记录: |