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 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 swift September 8, 2024 How to make Squircle shape in SwiftUI and how to easily convert it to a circle or a rectangle?

To create a squircle shape (a combination of a square and a circle, also known as a superellipse) in SwiftUI, you can define a custom shape by conforming to the Shape protocol and implementing the superellipse formula. The formula for a superellipse is:

question swiftui swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.