swiftui 无法更改接收器中的@State 值
swiftui cannot change @State value in sink
我现在正在学习swiftui,我是Whosebug的新手,我发现了一个问题,这是我的代码。我想更改 sink 中的@State nopubName,但是它不起作用,打印总是“Nimar”,我不知道为什么
struct ContentView: View {
@State var nopubName: String = "Nimar"
private var cancellable: AnyCancellable?
var stringSubject = PassthroughSubject<String, Never>()
init() {
cancellable = stringSubject.sink(receiveValue: handleValue(_:))
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
self.nopubName = value
print("in sink "+nopubName)
}
var body: some View {
VStack {
Text(self.nopubName)
.font(.title).bold()
.foregroundColor(.red)
Spacer()
Button("sink"){
stringSubject.send("World")
print(nopubName)
}
}
}
}
You should only access a state property from inside the view’s body, or from methods called by it.
https://developer.apple.com/documentation/swiftui/state
您可以在 ObservableObject
中使用该功能并更新 @Published
以保持 UI 更新
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
不需要使用Combine,如果在View
范围内,可以直接改变@State
变量的值
struct ContentView: View {
@State var nopubName: String = "Nimar"
var body: some View {
VStack {
Text(self.nopubName)
.font(.title).bold()
.foregroundColor(.red)
Spacer()
Button("sink"){
nopubName = "World"
}
}
}
}
我现在正在学习swiftui,我是Whosebug的新手,我发现了一个问题,这是我的代码。我想更改 sink 中的@State nopubName,但是它不起作用,打印总是“Nimar”,我不知道为什么
struct ContentView: View {
@State var nopubName: String = "Nimar"
private var cancellable: AnyCancellable?
var stringSubject = PassthroughSubject<String, Never>()
init() {
cancellable = stringSubject.sink(receiveValue: handleValue(_:))
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
self.nopubName = value
print("in sink "+nopubName)
}
var body: some View {
VStack {
Text(self.nopubName)
.font(.title).bold()
.foregroundColor(.red)
Spacer()
Button("sink"){
stringSubject.send("World")
print(nopubName)
}
}
}
}
You should only access a state property from inside the view’s body, or from methods called by it.
https://developer.apple.com/documentation/swiftui/state
您可以在 ObservableObject
中使用该功能并更新 @Published
以保持 UI 更新
https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app
不需要使用Combine,如果在View
范围内,可以直接改变@State
变量的值
struct ContentView: View {
@State var nopubName: String = "Nimar"
var body: some View {
VStack {
Text(self.nopubName)
.font(.title).bold()
.foregroundColor(.red)
Spacer()
Button("sink"){
nopubName = "World"
}
}
}
}