0

我正在使用这个.if效果很好的扩展,应该添加到 SwiftUI,但是在这种情况下它无法检查#available,因为无论如何#available may only be used as condition of an 'if', 'guard' or 'while' statement我怎样才能让它与这个一起工作.if

    //Does not compile for #available may only be used as condition of an 'if', 'guard' or 'while' statement
   ForEach...
   .if(#available(iOS 15.0, *)) { $0.refreshable {
                        
                    } }

extension View {
  @ViewBuilder
  func `if`<Transform: View>(
    _ condition: Bool,
    transform: (Self) -> Transform
  ) -> some View {
    if condition {
      transform(self)
    } else {
      self
    }
  }
}
4

1 回答 1

2

我通常会这样做.if(true),然后检查关闭内的可用性。不幸的是,我们无法检查if修饰符中的可用性。

例子:

struct ContentView: View {
    var body: some View {
        List {
            Text("Hello")
            /* More list items... */
        }
        .if(true) {
            if #available(iOS 15, *) {
                $0.refreshable {
                    //
                }
            } else {
                $0
            }
        }
    }
}

添加@ViewBuildertransform参数中,以便您可以在以下内容中返回不同View的类型if

extension View {
    @ViewBuilder func `if`<Transform: View>(_ condition: Bool, @ViewBuilder transform: (Self) -> Transform) -> some View {
        if condition {
            transform(self)
        } else {
            self
        }
    }
}
于 2021-08-16T19:00:56.763 回答