ForEach with Array of Custom Views inside ViewBuilder in swiftui

3k views Asked by At

I am new to iOS Development.Here I am trying to go for different destination views using foreach loop

struct NewView : View
{
var arrayofviews //here I need array of views
var body:some View
{
  List
  {
   ForEach(array)
   {(item) in
      NavigationLink(destination: item)
      {
       Text("Click Here")
      }
   }
  }
}
}

I tried following

var arrayofviews=[view1(),view2(),view3()] as! [Any]

then I am getting this error Cannot convert value of type 'view1' to expected element type 'Array.ArrayLiteralElement' (aka 'AnyView')

here view1,view2,view3 are custom views

struct view1:View
{
var body:Some View
{
Text("...")
...
}
}
//similarly view2 and view3 also
1

There are 1 answers

0
Sai Durga Mahesh On
struct NewView : View
{
var arrayofviews=[AnyView(view1()),AnyView(view2()),AnyView(view3())] as! [AnyView] //This helped
var body:some View
{
  List
  {
   ForEach(0..<array.count)
   {(index) in
      NavigationLink(destination: array[index])
      {
       Text("Click Here")
      }
   }
  }
}
}

Thanks 'Mohammad Rahchamani' for your suggestion !!!