Post

Replies

Boosts

Views

Activity

List with Sections: Odd Behaviour when item in list changes
I have a simple Demo App were I present Items in a List with two sections. The first sections shows the favourite items the second all other. The odd behaviour occurs if I change the isFav state. on iPhoneOS: When I select an item the DetailView will appear. if I change the isFav state (toggle) the DetailView will disappear Video: /Dx_t88YvEVw (usual platform) on iPadOS: When I select an item the DetailView will appear. if I change the isFav state (toggle) the DetailView will not disappear but in the side bar the selection [disappears] Video: /qq4jQNrqlBg (usual platform) // // ContentView.swift // Shared // // Created by Christian on 06.06.21. // import SwiftUI //MARK: - Data Model struct Item: Identifiable, Equatable, Hashable { var id = UUID().uuidString var isFav = false var text: String } struct ItemScoped: Identifiable, Equatable, Hashable { var id: String { return item.id } var item: Item var index: Int } //MARK: Store class ItemStore: ObservableObject { @Published var items = [Item(text: "Item 1"), Item(text: "Item 2"), Item(isFav: true, text: "Item 3"), Item(text: "Item 4")] func scopedItems(isFav: Bool) -> [ItemScoped] { let sItems: [ItemScoped] = items.compactMap { guard let idx = items.firstIndex(of: $0) else { return nil } //find(items, $0) return ItemScoped(item: $0, index: idx) } return sItems.filter { $0.item.isFav == isFav } } } //MARK: - Views struct ContentView: View { // usally this is @EnvironmetObject, due to simplicity I put it here @StateObject var store: ItemStore = ItemStore() var body: some View { NavigationView { List { Section(header: Text("Favorites")) { ForEach(store.scopedItems(isFav: true)) { scopedItems in NavigationLink( destination: DetailView(item: $store.items[scopedItems.index]), label: { RowView(item: $store.items[scopedItems.index]) }) } } Section(header: Text("Other")) { ForEach(store.scopedItems(isFav: false)) { scopedItems in NavigationLink( destination: DetailView(item: $store.items[scopedItems.index]), label: { RowView(item: $store.items[scopedItems.index]) }) } } } .navigationTitle("Items") } } } // MARK: Row View /// RowView for item, tapping the text toggle the `isFav` state struct RowView: View { @Binding var item: Item var body: some View { Label( title: { Text(item.text) }, icon: { item.isFav ? Image(systemName: "star.fill") : Image(systemName: "star")} ) } } // MARK: Detail View /// DetailView to change item `text` and toggle `isFav` state struct DetailView: View { @Binding var item: Item var body: some View { VStack { Spacer() .frame(height: 20.0) TextField("Title", text: $item.text) .background(Color.gray.opacity(0.2)) .padding(10) Toggle("is Fav", isOn: $item.isFav.animation()) .padding() Spacer() } .padding() } } // MARK: - Preview struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
1
0
586
Jun ’21