Вот упрощенная версия этого: < /p>
Код: Выделить всё
struct BeginWorkoutView: View {
@ObservedObject var templateManager = TemplateManager.shared
var body: some View {
NavigationView{
ScrollView{
Section("Start from scratch"){
HStack{
NavigationLink("New Workout"){
//new workout page
}
NavigationLink("New Template"){
CreateTemplateView( viewModel: CreateTemplateViewModel(), editMode: true)
}
}
}
Section("Start from template") {
ForEach(templateManager.templates, id: \.id.self) { template in
TemplateRowView(template: template)
}
}
}
}
}
}
< /code>
Я управляю своими данными в менеджере шаблонов. Я могу добавить новые тренировки, и они отображаются на моей странице BoundWorkOutView без проблем. Как я уже сказал, когда я редактирую заголовок, он не обновляется в BoundWorkOutView. Из того, что я могу сказать, список шаблонов Templatemanager обновляется, но, похоже, он не запускает пользовательский интерфейс. В настоящее время я использую наблюдаемую структуру объекта @Mainactor/ @, потому что я хочу поддерживать Pre-IOS 17.
@MainActor
final class TemplateManager: ObservableObject {
@Published private(set) var templates: [WorkoutTemplate] = []
static let shared = TemplateManager()
init(){
getTemplates()
}
func getTemplates() {
//gets templates from firebase
}
func updateTemplates(template: WorkoutTemplate) {
Task{
do {
//updates templates in firebase
//HERE is where the UI should be getting the signal to update. Obviously spot replacing the template didnt work, but replacing the entire thing wont work either.
var updated = templates
if let index = updated.firstIndex(where: { $0.id == template.id }) {
updated[index] = template
} else {
updated.append(template)
}
self.templates = updated
} catch {
print("unable to update templates")
}
}
}
}
@MainActor
final class CreateTemplateViewModel: ObservableObject {
@Published var template: WorkoutTemplate
var templateManager = TemplateManager.shared
init(template: WorkoutTemplate) {
self.template = template
}
init(){
self.template = WorkoutTemplate(name: "Workout Template", workoutModules: [])
}
func addTemplateList() {
templateManager.updateTemplates(template: template)
}
func removeTemplateList() {
templateManager.removeTemplateList(templateId: template.id)
}
}
< /code>
struct CreateTemplateView: View {
@StateObject var viewModel: CreateTemplateViewModel
var body: some View {
ScrollView{
StringTextField(preview: "Template Name", $viewModel.template.name )
.padding()
//shows editable modules for the template
Button("save"){
viewModel.addTemplateList()
}
}
}
}
< /code>
there are "hacks" out there like using notifications or combine to notify the UI to update, but I believe this should work if done correctly. I am mostly writing this to learn these data structures and i'm having a difficult time grasping this one so I'd definitely like to get to the bottom of it rather than slap a bandaid fix on it.
Подробнее здесь: https://stackoverflow.com/questions/795 ... t-updating
Мобильная версия