首页 > 解决方案 > Swift UI:使用数组中的随机元素更新视图

问题描述

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

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!-> 不能在属性初始化器中使用实例成员“问题”;属性初始化程序在 'self' 可用之前运行。这里的问题似乎是必须首先加载问题数组。
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 初学者,每次按下按钮时我都想不出如何更新显示的当前问题。有人对此有想法吗?
非常感谢!

标签: iosswiftswiftui

解决方案


试试下面的(scratchy)

@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 ?? ""
}

推荐阅读