【问题标题】:SwiftUI: How to not show "case none" in a ForEach loopSwiftUI:如何在 ForEach 循环中不显示“case none”
【发布时间】:2020-12-18 02:18:14
【问题描述】:

目前,我有一个显示所有图标案例的 foreach 循环。我想隐藏 case none 因为我的 EffectIcon 视图需要一个选定的案例。 父视图:

enum Icons: String,CaseIterable, Hashable {
    case overlayText = "Text"
    case image = "Image"
    case rotate = "Rotate"
    ...
    case none
}
struct EffectPanel: View {
    @State var currentIconSelected: Icons = .none
    @State var listIcons = [Bool](repeating: false, count: Icons.allCases.count)
    var body: some View {
        VStack {
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 10) {
                    ForEach(0..<listIcons.count, id: \.self) { i in
                        EffectIcon(icon: Icons(rawValue: Icons.allCases[i].rawValue)!, currentIconSelected: $currentIconSelected)
                    }
                }
                .background(Color.black)
            }
        }
    }
}

【问题讨论】:

    标签: foreach enums swiftui


    【解决方案1】:

    您可以尝试这样的方法来隐藏 .none 案例:

    ForEach(0..<listIcons.count, id: \.self) { i in
        if Icons(rawValue: Icons.allCases[i].rawValue)! != .none {
          EffectIcon(icon: Icons(rawValue: Icons.allCases[i].rawValue)!,
                     currentIconSelected: $currentIconSelected)
       }
    }
    

    【讨论】:

      【解决方案2】:

      这是可能的替代方案(只是更简单)

      ForEach(Icons.allCases, id: \.self) { i in
          if i != .none {
              EffectIcon(icon: Icons(rawValue: i.rawValue), currentIconSelected: $currentIconSelected)
          }
      }
      

      【讨论】:

      • 谢谢阿斯佩里!!这真的让我大开眼界,我将把它应用到我的所有代码中。另外,非常感谢您多次帮助我!
      【解决方案3】:

      您也可以将此static var 添加到您的enum

      enum Icons {
      
          static var selectableCases: [Icons] {
              var selectableCases = allCases
              selectableCases.removeLast()
              return selectableCases
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-18
        • 1970-01-01
        相关资源
        最近更新 更多