Quantcast
Channel: Active questions tagged crash - Stack Overflow
Viewing all articles
Browse latest Browse all 7197

SwiftUI using ForEach and onTapGesture to update selected element causing crash

$
0
0

I have some code that I am using, the idea is that the user selects a card they like and a sheet is presented to show more information about that card. The problem is, if I don't have the Text(selectedCard?.name ?? "Not selected") line, it crashes. I was just wondering what I don't understand about Swift/SwiftUI that is making this happen and how I could fix it (as I don't want it to say what card they have selected).

Full code:

import SwiftUIstruct CardsView: View {    @State private var cardlist = [Cards]()    @State private var showingSheet = false    @State private var selectedCard: Cards?    let columns = [        GridItem(.adaptive(minimum: 120))    ]    var body: some View {        NavigationView() {            ScrollView (.vertical, showsIndicators: false) {                Text("View our full collection of cards below:")                    .padding(.leading, 20)                    .frame(maxWidth: .infinity, alignment: .leading)                Text(selectedCard?.name ?? "Not selected") // This line stops it from crashing                    LazyVGrid(columns: columns, spacing: 10) {                        ForEach(cardlist, id: \.name) { thecard in                            CardItem(card: thecard)                                .onTapGesture {                                    selectedCard = thecard                                    showingSheet.toggle()                                }                        }                    }                    .padding([.leading, .trailing])                Spacer()            }            .navigationTitle("Cards")        }        .sheet(isPresented: $showingSheet) {            SpecificCardView(card: selectedCard!)        }        .onAppear() {            loadCards()        }    }    func loadCards() {        ...    }}

Viewing all articles
Browse latest Browse all 7197

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>