微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SwiftUI:在另一个状态变量的值发生变化时从 CoreData 重置 TextField 值

如何解决SwiftUI:在另一个状态变量的值发生变化时从 CoreData 重置 TextField 值

我有一个 ContentView 和一个 NumericView。 selectedindex 是 ContentView 中的 @State。我想要的是,如果 selectedindex 发生变化,它应该从 CoreData 重置 NumericView 中的答案字段。下面是代码。 “av”包含来自 CoreData 的答案字段的值。

struct NumericEntry: View {
    @EnvironmentObject var questionAnswerStore: QuestionAnswerStore
    @State var answer: String
    
    
    var questionIndex: Int

    init(questionIndex: Int,av: String) {
        self.questionIndex = questionIndex
        _answer = State(initialValue: av)
    }
    
    var body: some View {
        vstack {
            TextField("Answer",text: $answer)
                .textFieldStyle(CustomTextFieldStyle())
                .onChange(of: answer) { newValue in
                    self.questionAnswerStore.getUserAttemptData(selectedindex: questionIndex).answer = newValue
                    PersistenceController.shared.saveContext()
                }
                .keyboardType(.decimalPad)
                .padding()
            
        }
    }
  
    private struct CustomTextFieldStyle : TextFieldStyle {
        public func _body(configuration: TextField<Self._Label>) -> some View {
            configuration
                .padding(10)
                .background(
                    RoundedRectangle(cornerRadius: 5)
                        .strokeBorder(Color.secondary.opacity(0.5),linewidth: 1))
            
        }
    }
}
struct ContentView: View {


   @State var selectedindex: Int = 0
   @Observedobject private var questionAnswerStore: QuestionAnswerStore = QuestionAnswerStore.sharedInstance
    

   var body: some View {
      NumericEntry(questionIndex: selectedindex,av: self.questionAnswerStore.getUserAttemptData(selectedindex: selectedindex).answer ?? "")

// some code that keeps changing the value of selectedindex
  }
}
    

我在某处读到 _stateVariable = State(initialValue: "abcd") 应该设置 @State stateVariable 的状态。上面代码中的代码

_answer = State(initialValue: av)

执行正常,但到达时

TextField("Answer",text: $answer)

$answer 仍然是“”。

我更喜欢一种解决方案,我什至不必从父组件发送“av”,只需 selectedindex 应该检查 QuestionAnswerStore 以获取“answer”的值。这可以使用 .onAppear 解决,但在我的情况下,NumericView 只出现一次,然后它的父级只是不断更改 selectedindex 值,因此不会再次调用 onAppear。

当然,如果这是不可能的,那么上面使用“av”的出路是什么?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。