GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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+

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and more!

Learn more here

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.