如何将2个内容参数传递到SwiftUI视图



我有一个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作为目标操作系统版本。

你可能会忍不住问,";为什么不在使用点使用2张卡并在那里对齐呢&";。答案是,在向SwiftUI过渡的过程中,我正在尝试在UIKit中复制一些东西。

您需要为泛型提供不同的内容类型(因为通常它们可能不同(

因此,是一个解决方案

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()
}
// ...
}

最新更新