【问题标题】:How to apply strikethrough() to a tapped foreach Text item in SwiftUI?如何在 SwiftUI 中将删除线()应用于点击的 foreach 文本项?
【发布时间】:2020-12-28 23:08:33
【问题描述】:

我正在尝试对 ForEach 循环中任何被点击的文本项应用删除线:

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.
                            })
                }
            }
        }
    }
    
}

有没有一种简单的方法可以使用@State var 来应用条件,以跟踪何时应用删除线()?我在想唯一的方法是将一个属性放入 listObject 来跟踪它是否被击中,然后使用它来将 true/false 应用于删除线()修饰符。但这似乎是意大利面条代码?

【问题讨论】:

    标签: swiftui strikethrough swiftui-foreach


    【解决方案1】:

    如果你需要它持久化,那么你绝对应该把它放到模型中。否则,@State 仅用于运行时,您可以在子视图中执行,例如

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

    和行视图:

    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()
            })
      }
    }
    

    【讨论】:

    • 非常感谢,这正是我要找的!
    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2017-11-14
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多