【问题标题】:if statement inside of ForEach in iOS SwiftUIiOS SwiftUI 中 ForEach 内的 if 语句
【发布时间】:2020-08-05 17:52:13
【问题描述】:

我在 iOS SwiftUI(Xcode 版本 11.6)的 ForEach 中有一个“if”,它可以正常工作。

struct ContentView: View {
    var body: some View {
        List {
            ForEach(0 ..< 10) {(i: Int) in
                if i % 2 == 0 {
                    Text(String(i))
                }
            }
        }
    }
}

现在我想做同样的事情,但使用字符串数组而不是半开范围的 Ints。

struct ContentView: View {
    let states: [String] = [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California"
    ];
    
    var body: some View {
        List {
            ForEach(states, id: \.self) {(state: String) in
                if state.hasPrefix("Al") {
                    Text(state)
                }
            }
        }
    }
}

我从这个 ForEach 得到的错误信息是

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

出了什么问题?我很困惑,因为 Apple 的 SwiftUI 教程在第 3 节第 1 步的 ForEach 中有一个“if” https://developer.apple.com/tutorials/swiftui/handling-user-input
提前谢谢你。

【问题讨论】:

    标签: ios if-statement foreach swiftui


    【解决方案1】:

    您可以尝试以下方法:

    struct ContentView: View {
        ...
        
        var body: some View {
            List {
                ForEach(states, id: \.self) { state in
                    self.stateView(state: state)
                }
            }
        }
        
        @ViewBuilder
        func stateView(state: String) -> some View {
            if state.hasPrefix("Al") {
                Text(state)
            }
        }
    }
    

    这样您的代码也可能更具可读性。

    【讨论】:

      【解决方案2】:

      一种可能的方法是使用Group:

      struct ContentView: View {
          let states: [String] = [
              "Alabama",
              "Alaska",
              "Arizona",
              "Arkansas",
              "California"
          ];
          
          var body: some View {
              List {
                  ForEach(states, id: \.self) {(state: String) in
                      Group {
                          if state.hasPrefix("Al") {
                              Text(state)
                          }
                      }
                  }
              }
          }
      }
      

      有些视图比其他视图更灵活一些。例如,在 HStack 或 VStack 中,您甚至可以放置多个(子)View,而在 ForEach 中则不能。 Group 有很大的灵活性,但不影响布局,所以通常你可以用它来包装复杂的视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-15
        • 1970-01-01
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多