问题描述
即使我看到正在调用updateMessage()
,我也无法更新ExampleView的message
变量.这是我的简化/复杂的SwiftUI Playground代码示例,无法正常工作.在updateMessage()
中调用时,message
变量不会更新.结果,UI Text()
也未更新.
I'm unable to update the ExampleView's message
var even though I can see updateMessage()
is being called. Here is my simplified/convoluted SwiftUI example of Playground code that isn't working. The message
var does not get updated when called in updateMessage()
. As a result, the UI Text()
is not updated either.
为什么@State变量message
不更新?什么是正确的更新方式?
Why is the @State var message
not updating? What is the correct way to update it?
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
let coloredLabel = ExampleView()
var body: some View {
VStack {
coloredLabel
.foregroundColor(Color.red)
.padding()
Button(action: {
self.coloredLabel.updateMessage()
}) {
Text("Press me")
}
}
}
}
struct ExampleView: View {
@State private var message: String = "Hello"
var body: some View {
Text(self.message)
}
func updateMessage() {
print("updateMessage ran") // this prints
self.message = "Updated"
}
}
PlaygroundPage.current.setLiveView(ContentView())
推荐答案
您应该只更改视图的State
内部,它是自己的主体块.如果需要从父视图更改它,则可能需要将值从父视图传递给它,并改为Binding
.
You should only change State
of a view Inside it's own body block. If you need to change it from a parent view, you may want to pass the value to it from parent and make it Binding
instead.
struct ContentView: View {
@State private var message = "Hello"
var body: some View {
VStack {
ExampleView(message: $message)
.foregroundColor(Color.red)
.padding()
Button("Press me") {
self.message = "Updated"
}
}
}
}
struct ExampleView: View {
@Binding var message: String
var body: some View {
Text(message)
}
}
如果需要将消息封装在ExampleView
内,则可以使用Bool
(或enum
等)代替
If you need to encapsulate messages inside the ExampleView
, you can use a Bool
(or an enum
or etc) instead:
struct ContentView: View {
@State private var updated = false
var body: some View {
VStack {
ExampleView(isUpdated: $updated)
.foregroundColor(Color.red)
.padding()
Button("Press me") {
self.updated = true
}
}
}
}
struct ExampleView: View {
@Binding var isUpdated: Bool
private var message: String { isUpdated ? "Updated" : "Hello" }
var body: some View {
Text(message)
}
}
这篇关于无法更新/修改SwiftUI View的@state var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!