我正在尝试在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 ?? ""
}