Swift UI:使用数组中的随机元素更新视图

尼克拉斯

我正在尝试在Swift中更新视图,但我不知道如何使它工作。我的应用有问题,这些问题是从Core数据加载的。从那里,应该在顶部显示一个随机问题。保存答案后(通过按按钮进行操作:保存),应显示一个新的随机问题。

struct RecordView: View {
@Environment(\.managedObjectContext) var moc


@FetchRequest(entity: Question.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Question.question, ascending: false)])
var questions: FetchedResults<Question>
var currentQuestion: String { return questions.randomElement()!.question! }

@State private var newEntryText = ""


    var body: some View {
         VStack {
            Section(header: Text(currentQuestion)){
                       TextField("New entry", text: self.$newEntryText)
                        .padding(100)

                       HStack {
                           SwiftSpeech.RecordButton().scaleEffect(0.8).swiftSpeechToggleRecordingOnTap(locale: Locale(identifier: "de"), animation: .spring(response: 0.3, dampingFraction: 0.5, blendDuration: 0))
                               .onRecognize(update: self.$newEntryText)

                        Button(action: save)
                           {
                            Image(systemName: "plus.circle.fill").foregroundColor(.green).imageScale(.large).scaleEffect(2.0)
                               }

                       }
                   }.automaticEnvironmentForSpeechRecognition()
    }
}

    func save() {
        let newEntry = Entry(context: self.moc)
             newEntry.text = self.newEntryText
             newEntry.createdAt = Date()
        do {
            try self.moc.save()
        }catch{
            print(error)
        }
        self.newEntryText = ""
        print(currentQuestion)

    }

我试过的

1)@State var currentQuestion: String = questions.randomElement()!.question!->无法在属性初始化程序中使用实例成员“问题”;属性初始化程序在“自我”可用之前运行。这里的问题似乎是问题数组必须先加载。
2)var currentQuestion: String { return questions.randomElement()!.question! }->在这里,每次访问currentQuestion都会重新计算,但是View不会更新。如果我移动questions.randomElement()!. question,也是一样!到Text()组件。
3)lazy var currentQuestion = questions.randomElement()!.question!->无法在不可变值上使用变异getter:“ self”是不可变的(在Text()组件上)。懒惰的部分应该已经解决了我在1)解决方案中遇到的问题,但是后来我无法在Text()组件上使用它。

...以及其他一些小的变化。我是一个Swift / Swift UI初学者,并且在每次按下按钮时如何更新显示的当前问题的想法已经用尽。有人对此有想法吗?
非常感谢!

他的脾气

尝试以下方法(抓痒)

@State var currentQuestion: String = "" // as state !!

var body: some View {
    VStack {
        Section(header: Text(currentQuestion)){

           // ... other your code here

        }.automaticEnvironmentForSpeechRecognition()
    }.onAppear {
        self.nextQuestion()    // << here !!
    }
}

...

func save() {
    // ... other your code here

   self.nextQuestion()         // << here !!
}

private func nextQuestion() {
   self.currentQuestion = questions.randomElement()?.question ?? ""
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章