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 iOS April 2, 2024 How to open a second view from first view in iOS using SwiftUI?

In SwiftUI, you can open another view (or navigate to another view) on the click of a button by utilizing navigation views and navigation links. Here’s a basic example of how to achieve this:

question swiftui March 29, 2024 How to group different style modifiers and reuse them across multiple SwiftUI views?

In SwiftUI, you can create custom view modifiers to encapsulate common styling configurations and reuse them across different views. Here’s how you can create and reuse a custom view modifier:

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.