How to have a dynamic List of Views using SwiftUI
Looks like the answer was related to wrapping my view inside of AnyView
struct ContentView : View {
var myTypes: [Any] = [View1.self, View2.self]
var body: some View {
List {
ForEach(0..<myTypes.count) { index in
self.buildView(types: self.myTypes, index: index)
}
}
}
func buildView(types: [Any], index: Int) -> AnyView {
switch types[index].self {
case is View1.Type: return AnyView( View1() )
case is View2.Type: return AnyView( View2() )
default: return AnyView(EmptyView())
}
}
}
With this, i can now get view-data from a server and compose them. Also, they are only instanced when needed.
You can use dynamic list of subviews, but you need to be careful with the types and the instantiation. For reference, this is a demo a dynamic 'hamburger' here, github/swiftui_hamburger.
// Pages View to select current page
/// This could be refactored into the top level
struct Pages: View {
@Binding var currentPage: Int
var pageArray: [AnyView]
var body: AnyView {
return pageArray[currentPage]
}
}
// Top Level View
/// Create two sub-views which, critially, need to be cast to AnyView() structs
/// Pages View then dynamically presents the subviews, based on currentPage state
struct ContentView: View {
@State var currentPage: Int = 0
let page0 = AnyView(
NavigationView {
VStack {
Text("Page Menu").color(.black)
List(["1", "2", "3", "4", "5"].identified(by: \.self)) { row in
Text(row)
}.navigationBarTitle(Text("A Page"), displayMode: .large)
}
}
)
let page1 = AnyView(
NavigationView {
VStack {
Text("Another Page Menu").color(.black)
List(["A", "B", "C", "D", "E"].identified(by: \.self)) { row in
Text(row)
}.navigationBarTitle(Text("A Second Page"), displayMode: .large)
}
}
)
var body: some View {
let pageArray: [AnyView] = [page0, page1]
return Pages(currentPage: self.$currentPage, pageArray: pageArray)
}
}
if/let
flow control statement cannot be used in a @ViewBuilder
block.
Flow control statements inside those special blocks are translated to structs.
e.g.
if (someBool) {
View1()
} else {
View2()
}
is translated to a ConditionalValue<View1, View2>
.
Not all flow control statements are available inside those blocks, i.e. switch
, but this may change in the future.
More about this in the function builder evolution proposal.
In your specific example you can rewrite the code as follows:
struct ContentView : View {
let elements: [Any] = [View1.self, View2.self]
var body: some View {
List {
ForEach(0..<elements.count) { index in
if self.elements[index] is View1 {
View1()
} else {
View2()
}
}
}
}
}
I found a little easier way than the answers above.
Create your custom view.
Make sure that your view is Identifiable
(It tells SwiftUI it can distinguish between views inside the ForEach by looking at their id property)
For example, lets say you are just adding images to a HStack, you could create a custom SwiftUI View like:
struct MyImageView: View, Identifiable {
// Conform to Identifiable:
var id = UUID()
// Name of the image:
var imageName: String
var body: some View {
Image(imageName)
.resizable()
.frame(width: 50, height: 50)
}
}
Then in your HStack:
// Images:
HStack(spacing: 10) {
ForEach(images, id: \.self) { imageName in
MyImageView(imageName: imageName)
}
Spacer()
}