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.

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on April 2, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui swift October 7, 2024 How to zoom in and zoom out a SwiftUI view?

In a macOS or iOS app, you can easily add a zoom feature to any SwiftUI view with the scaleEffect modifier. In the below example, I am using a Slider to control the zoom level. Here’s how you can implement zooming in and out with a slider:

question swiftui swift August 31, 2024 @StateObject vs @ObservedObject in SwiftUI

In SwiftUI, both @StateObject and @ObservedObject are property wrappers used to manage state in your views, specifically when working with objects that conform to the ObservableObject protocol. However, they serve slightly different purposes and have different use cases. Here’s a breakdown:

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: