0

I'm trying to create a simple todo-list app using Swift for VisionOS. So far, when the user creates their first Todo-List, the user can name it, select it and add todos into the list. However, when the user tries to create more Todo-Lists, it is not possible to select them.

import SwiftUI

struct ContentView: View {
    @State private var TodoLists: [TodoList] = []
    @State private var selectedTodoList: TodoList? = nil
    @State private var showAddListAlert: Bool = false
    @State private var newListTitle: String = ""
    @State private var nextListID: Int = 0
    
    var body: some View {
        NavigationSplitView {
            List(TodoLists) { list in
                Button(list.title) {
                    selectedTodoList = list
                }
            }
            .navigationTitle("Todo lists")
            .toolbar {
                Button("Add") {
                    showAddListAlert.toggle()
                }
            }
            .alert("Add Todo List", isPresented: $showAddListAlert) {
                TextField("Todo List Title", text: $newListTitle)
                Button("Cancel", role: .cancel, action: {})
                Button("Create") {
                    let list = TodoList(title: newListTitle.isEmpty ? "List \(nextListID)" : newListTitle, items: [], id: UUID())
                    TodoLists.append(list)
                    nextListID += 1
                }
            }
        } detail: {
            if let selectedTodoList {
                TodoListView(list: selectedTodoList)
            }
        }
    }
}

I would have thought that Button(list.title) { selectedTodoList = list } would set the selected the selected list. Perhaps the child view (TodoListView) is interfering:

import SwiftUI

struct TodoListView: View {
    @State var list: TodoList
    @State private var showAddTodoAlert: Bool = false
    @State private var newTodoTitle: String = ""
    
    var body: some View {
        List(list.items) { item in
            Text(item.title)
        }
        .navigationTitle("Details for \(list.title)")
        .toolbar {
          Button("Add Todo") {
            showAddTodoAlert.toggle()
          }
        }
        .alert("Add Todo", isPresented: $showAddTodoAlert) {
            TextField("Todo Title", text: $newTodoTitle)
            Button("Cancel", role: .cancel, action: {})
            Button("Create") {
                let todo = TodoItem(title: newTodoTitle, isDone: false)
                list.items.append(todo)
            }
        }
        .id(list.id)
    }
    
    
}
Marcell
  • 1
  • 3

1 Answers1

0

Writing .id(selectedTodoList.id) in the detail view of the ContentView solved the issue. Apparently, this is a SwiftUI bug that was causing problems.

Marcell
  • 1
  • 3