Loading...

How to declare an array of Views in SwiftUI?

question swiftui
Ram Patra Published on April 2, 2024

In SwiftUI, you can declare an array of View using the standard Swift array syntax. Here’s how you can do it:

import SwiftUI

struct ContentView: View {
    // Declare an array of View
    var views: [AnyView] = [
        AnyView(Text("View 1")),
        AnyView(Text("View 2")),
        AnyView(Text("View 3"))
    ]
    
    var body: some View {
        VStack {
            // Use ForEach to iterate over the array of views
            ForEach(views, id: \.self) { view in
                view
                    .padding()
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

In this example:

  • We’ve declared an array views of type [AnyView].
  • Each element of the array is of type AnyView, allowing us to store any type of View.
  • We’ve initialized the array with three Text views wrapped in AnyView.
  • Inside the body of the ContentView, we use a VStack to arrange the views vertically.
  • We use ForEach to iterate over the array of views and display each one.

You can replace the Text views with any other type of view you want to include in the array. This approach allows you to dynamically create and display views based on the contents of the array.

Ram Patra Published on April 2, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift October 30, 2023 How to convert Color type to hex and vice-versa while retaining alpha information?

The below should work both on macOS and iOS with one minor change. That is, use UIColor instead of NSColor if you’re planning to use it for iOS.

question swiftui March 6, 2023 How to render the icon on a menu bar as a template in SwiftUI?

Setting your app’s icon on the menu bar as a template makes it to adapt to light and dark modes automatically without you doing anything. To do this, you have to use this constructor of MenuBarExtra class.

question swiftui macOS January 26, 2024 How to hide the title bar in a SwiftUI macOS app?

Let’s say you have a view named ContentView and your main App file looks like this: