gpt4 book ai didi

ios - View 更新期间我正在修改什么状态?

转载 作者:行者123 更新时间:2023-11-29 05:28:41 24 4
gpt4 key购买 nike

我有一个 CoreData 对象 Day,我正在该 View 中编辑它,当处于“编辑”模式时,该卡允许使用 Picker View ,然后使用 TextField 允许用户输入。这些都按预期工作,但是当我点击“完成”时,它运行 saveEditToDay() 函数,该函数只是将它们保存到 Day 变量中。这会导致线程 1:EXC_BREAKPOINT (code=1, subcode=0x1cffc77e0) 崩溃,并给出提示在 View 更新期间修改状态,这将导致未定义的行为。。我不清楚在这种情况下我要修改什么状态?

这是 View :


import SwiftUI

struct EditCard: View {

@Binding var day: Day?
var timeOfDay: Time
@State var isEditing: Bool = false
@State var selectedRating = 0
@State var description = ""
var ratings = Rating.getAllRatings()

// MARK: - Body
var body: some View {
VStack(alignment: .leading) {
HStack {
Text(timeOfDay.rawValue).font(.headline)
Spacer()
Button(action: {
if self.isEditing { self.saveEditToDay() }
self.isEditing.toggle()
}, label: { self.isEditing ? Text("Done") : Text("Edit") })
.foregroundColor(Color("PrimaryColour"))
}

Divider()

VStack(alignment: .leading) {
Text("RATING")
.font(.caption)
.foregroundColor(Color(UIColor.systemGray))

if isEditing {
Picker(selection: $selectedRating, label: Text("")) {
ForEach(0 ..< ratings.count) {
Text(self.ratings[$0]).tag([$0])
}
}
} else {
Text(day!.getRating(for: timeOfDay))
}

}.padding(.trailing)

VStack(alignment: .leading) {
Text("REASON")
.font(.caption)
.foregroundColor(Color(UIColor.systemGray))

if isEditing {
TextField(description, text: $description)
} else {
Text(description)
.multilineTextAlignment(.leading)
.lineLimit(nil)
}

}
}
.padding()
.background(Color(UIColor.secondarySystemGroupedBackground))
.cornerRadius(10)
.onAppear { self.setSelected() }
.onDisappear{ self.saveEditToDay(); print("Toodles") }
}

// MARK: - Functions
func setSelected() {
guard let day = day else { return }
self.selectedRating = ratings.firstIndex(of: day.getRating(for: timeOfDay))!
self.description = day.getDescription(for: timeOfDay)
}

func saveEditToDay() {
guard let day = day else { return }
day.setRating(rating: ratings[selectedRating], for: timeOfDay)
day.setDescription(description: description, for: timeOfDay)
}
}

这里是我正在调用的 NSManagedObject 的扩展:

func setRating(rating: String, for time: Time) {
switch time {
case .morning: self.morning = rating;
case .afternoon: self.afternoon = rating;
case .evening: self.evening = rating;
}
}

func setDescription(description: String, for time: Time) {
switch time {
case .morning: self.morningDescription = description;
case .afternoon: self.afternoonDescription = description;
case .evening: self.eveningDescription = description;
}
}

最佳答案

您正在 onApear() 中调用 setSelected(),这会修改标记为 @State 的两个变量:selectedRating 描述。这意味着当 View 被绘制或重绘时,您正在更改定义在过程中途绘制的内容的变量。onApear() 是触发后台刷新的好地方,但不会立即修改任何 @State 变量。您可能应该编写一个初始化程序,将绑定(bind)到 DayTime 设置其他两个变量,就像您在 setSelected() 中所做的那样。

关于ios - View 更新期间我正在修改什么状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57892413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com