簡體   English   中英

如何將 2 個內容參數傳遞給 SwiftUI 視圖?

[英]How can I pass 2 content parameters to a SwiftUI View?

我有一個卡片視圖,它接受一個內容參數以顯示在有邊框的視圖中。

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 張卡片並將它們對齊?”。 答案是,我試圖在 UIKit 中復制一些東西,以過渡到 SwiftUI。

您需要為 generics 提供不同的內容類型(因為通常它們可能不同)

所以修復將是

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

// ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM