代码之家  ›  专栏  ›  技术社区  ›  Ilja

如何使视图扩展应用于自身的修改器,并接收内容?

  •  0
  • Ilja  · 技术社区  · 2 年前

    我有以下模式,我经常在整个应用程序中重复,所以我试图将其作为视图扩展,即(注意 someCondition 并不总是存在,也可以只是一个简单的视图)

        .edgesIgnoringSafeArea(.bottom)
        .safeAreaInset(edge: .bottom) {
          if someCondition {
            SomeView()
          }
        }
    

    到目前为止,我试过这样的东西

    func footer<Content: View>(content: View) -> some View {
      self
        .edgesIgnoringSafeArea(.bottom)
        .safeAreaInset(edge: .bottom) {
          content
        }
    }
    

    但是这样使用它会产生各种错误

    VStack {}
      .footer {
         // any valid view code
      }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Sweeper    2 年前

    footer 应采用函数类型 () -> Content ,因为你想通过一个闭包。参数也应该是 @ViewBuilder ,以便您可以编写 if 这样的声明。

    // in a View extension...
    func footer<Content: View>(@ViewBuilder content: () -> Content) -> some View {
      self
        .edgesIgnoringSafeArea(.bottom)
        .safeAreaInset(edge: .bottom) {
          content()
        }
    }