UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Pass an array of subviews to a view

Forums > SwiftUI

@frios  

I have created a Swift Package that creates multiple PageTabViews from an array of content that is passed to it:

import SwiftUI

public struct WhatsNewView<Content: View>: View {

    let content: [Content]

    public init(content: [Content]){
        self.content = content
    }

    public var body: some View {
        TabView {
            ForEach(0..<content.count, id: \.self) { pageNum in
                WhatsNewPage(content: content[pageNum], pageNum: pageNum + 1, totalPages: content.count)
            }
        }
        .background(Color.white)
        .ignoresSafeArea()
        .tabViewStyle(PageTabViewStyle())
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
    }
}

When I call it I want to pass in any kind of simple or complex view to fill each page. Right now, I can pass in an array of simple text views like so:

import SwiftUI
import WhatsNew

@main
struct mFood_Vendor: App {
    @State var showWhatsNew = false
    let whatsNew = WhatsNew()

    var page1 = Text("Hello World")

    var page2 = Text("Goodbye World")

    var body: some Scene {
        WindowGroup {
            ContentView()
            .fullScreenCover(isPresented: $showWhatsNew, content: {
                let content = [page1, page2]
                WhatsNewView(content: content)
            })
            .onAppear(perform: {
                whatsNew.checkForUpdate(showWhatsNew: $showWhatsNew)
            })

        }
    }
}

I want page1 and page2 to be whatever content a person wants to see on the What's New pages. But if I change those vars to anything different, like a text and an Image, I get a "Failed to produce diagnostic for expression" error.

Ideally, I would like to be able to pass in something like:

struct page1: View {
    var body: some View {
      VStack {
        Text("something")
        Image("plus")
       }
     }
}

Any help would be appreciated. THANKS!

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.