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 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 macos September 3, 2024 How to open and close windows programmatically in SwiftUI?

To open or close a window programmatically from outside that window using environment variables, you need to leverage the new openWindow (macOS 13+) and dismissWindow (macOS 14+) environment variables. This environment variables allow you to programmatically open and close a window by its identifier.

question swiftui swift September 13, 2024 How to add a character limit to a TextField in SwiftUI?

To add a character length limit to a TextField in SwiftUI, you can use a combination of Swift’s .onChange, .onPasteCommand modifier, and string manipulation to limit the number of characters the user can enter.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.