2

我试图弄清楚如何改变不同的值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主视图中永远不会收到更改通知。我该怎么做才能在你们知道的主视图中获得更改通知?

我会非常感谢你的帮助

4

1 回答 1

2

您必须使用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)")
        }
    }
}
于 2020-10-18T22:07:54.987 回答