SwiftUI:检测@State变量何时在其@Binding中发生变化
SwiftUI: detecting when @State variable has change in their @Binding
我想知道如何改变不同 View
的值。下面是我的主要观点的实现:
import SwiftUI
import Combine
struct ContentView: View {
@State private var isPresented: Bool = false
@State private var textToProces = "" {
didSet{
print("text: oldValue=\(oldValue) newValue=\(textToProces)")
}
}
var body: some View {
ZStack{
VStack{
Button("Show Alert"){
self.isPresented = true
}.background(Color.blue)
}
ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
}
}
}
在这个视图中,我正在尝试更改 textToProces
变量:
struct AnotherView: View {
@Binding var isShown: Bool
@Binding var textToProcess: String
var title: String = "Add Item"
let screenSize = UIScreen.main.bounds
var body: some View {
VStack {
Button(action: {
self.textToProcess = "New text"
self.isShown = false
}, label: {
Text("dissmis")
})
Text(self.textToProcess)
}
.background(Color.red)
.offset(y: isShown ? 0 : screenSize.height)
}
}
当我更改此行 self.textToProcess = "New text"
上的值时,主视图中的 textToProcess
永远不会收到更改通知。你们知道我该怎么做才能在主视图中收到更改通知吗?
非常感谢你的帮助
您必须使用 onChange
修饰符来跟踪对 textToProces
的更改。
import SwiftUI
import Combine
struct ContentView: View {
@State private var isPresented: Bool = false
@State private var textToProces = ""
var body: some View {
ZStack{
VStack{
Button("Show Alert"){
self.isPresented = true
}.background(Color.blue)
}
ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
}
.onChange(of: textToProces) { value in
print("text: \(value)")
}
}
}
我想知道如何改变不同 View
的值。下面是我的主要观点的实现:
import SwiftUI
import Combine
struct ContentView: View {
@State private var isPresented: Bool = false
@State private var textToProces = "" {
didSet{
print("text: oldValue=\(oldValue) newValue=\(textToProces)")
}
}
var body: some View {
ZStack{
VStack{
Button("Show Alert"){
self.isPresented = true
}.background(Color.blue)
}
ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
}
}
}
在这个视图中,我正在尝试更改 textToProces
变量:
struct AnotherView: View {
@Binding var isShown: Bool
@Binding var textToProcess: String
var title: String = "Add Item"
let screenSize = UIScreen.main.bounds
var body: some View {
VStack {
Button(action: {
self.textToProcess = "New text"
self.isShown = false
}, label: {
Text("dissmis")
})
Text(self.textToProcess)
}
.background(Color.red)
.offset(y: isShown ? 0 : screenSize.height)
}
}
当我更改此行 self.textToProcess = "New text"
上的值时,主视图中的 textToProcess
永远不会收到更改通知。你们知道我该怎么做才能在主视图中收到更改通知吗?
非常感谢你的帮助
您必须使用 onChange
修饰符来跟踪对 textToProces
的更改。
import SwiftUI
import Combine
struct ContentView: View {
@State private var isPresented: Bool = false
@State private var textToProces = ""
var body: some View {
ZStack{
VStack{
Button("Show Alert"){
self.isPresented = true
}.background(Color.blue)
}
ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
}
.onChange(of: textToProces) { value in
print("text: \(value)")
}
}
}