How to apply strikethrough() to a tapped foreach Text item in SwiftUI?

4.8k Views Asked by At

I'm trying to apply a strikethrough to any tapped Text items in a ForEach loop:

struct BrandListView: View {
    @ObservedObject var list: ListObject
                                
    var body: some View {
        ScrollView {
            VStack {
                ForEach(list.items) { items in
                        Text(item.name)
                            .strikethrough(//?)
                            .onTapGesture(perform: {
                                // on tap, apply strikethrough only to this item.
                            })
                }
            }
        }
    }
    
}

Is there an easy way to apply a condition using @State var, to track when to apply strikethrough() or not? I'm thinking the only way is to put a property into the listObject that tracks whether it is striked or not, and then use that to apply true/false to the strikethrough() modifier. But that seems like spaghetti code?

1

There are 1 best solutions below

2
On BEST ANSWER

If you need it persistent, then definitely you should put it into model. Otherwise, @State is only for run-time, you can do it in subview, like

ForEach(list.items) { item in
    RowView(item: item)
}

and RowView:

struct RowView: View {
  let item: Your_Item_Type

  @State private var stroken = false

  var body: some View {
    Text(item.name)
        .strikethrough(stroken)
        .onTapGesture(perform: {
            self.stroken.toggle()
        })
  }
}