如何将两个内容参数传递给SwiftUI视图?

3
我有一个Card视图,需要传入一个内容参数来在边框视图中显示。
public struct Card<Content: View>: View {
    private let content: Content

    public init(@ViewBuilder content: () -> Content) {
            self.content = content()
    }
    
    public var body: some View {
       content
          .padding(16)
          .frame(maxWidth: .infinity)
          .background(TileShape(cornerRadius: 8, backgroundColor: backgroundColor))
          .clipShape(RoundedRectangle(cornerRadius: 8))
   }
}

我想要介绍一个堆叠式卡片。或许类似这样:
public struct Card<Content: View>: View {
    private let content: Content
    private let stackedContent: Content

    public init(@ViewBuilder content: () -> Content, @ViewBuilder stackedContent: () -> Content) {
            self.content = content()
            self.stackedContent = stackedContent()
    }
    
    public var body: some View {
        ZStack {
           content
              .padding(16)
              .frame(maxWidth: .infinity)
              .background(TileShape(cornerRadius: 8, backgroundColor: backgroundColor))
              .clipShape(RoundedRectangle(cornerRadius: 8))
              
            stackedContent
                /// put stuff here to align it correctly
        }
   }
}

虽然我可以创建这个初始化器,但问题在于如何给它内容。

在我的调用代码中,我有:

   Tile {
      Text("Card contents")
   }

当我尝试引入第二张卡片时,在编译期间会出现段错误。
   Tile(stackedContent: stackedCard) {
      Text("Base Card Contents")
   }


    @ViewBuilder
    var stackedCard: Card<some View> {
        Card {
            Text("Stacked Card Here")
        }
    }

我的目标能否通过SwiftUI实现?我只能使用iOS 14作为目标操作系统版本。

你可能会问:“为什么不在使用时只使用两张卡片并将它们对齐?”答案是,我正在尝试在从UIKit过渡到SwiftUI时复制某些东西。

1个回答

3
您需要针对泛型提供不同的内容类型(因为它们通常会有所不同)。
因此,解决方法是:
public struct Card<Content1: View, Content2: View>: View {
    private let content: Content1
    private let stackedContent: Content2

    public init(@ViewBuilder content: () -> Content1, @ViewBuilder stackedContent: () -> Content2) {
            self.content = content()
            self.stackedContent = stackedContent()
    }

// ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接