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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.