Search code examples
swiftuiviewswiftuiuipageviewcontroller

SwiftUI - PageView - Pass in different Views


I successfully implemented PageView within SwiftUI via thread:
How to implement PageView in SwiftUI?

Passing in multiple Views via an Array works like a charm, as long as all views are of the same struct.
PageView([TestView(), TestView()]).
However, I'd like to pass in different views.
PageView([TestView(), AnotherView(), DifferentView()]).

All views are of SwiftUI type:
struct NAME : View { code }

When I try to add different structs to an array I get the following error message:

var pageViewViewArray = [TestView(), AnotherView(), DifferentView()]

Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional.
Insert' as [Any]

By casting it to:

var pageViewViewArray = [TestView(), AnotherView(), DifferentView()] as! [Any]
PageView(pageViewViewArray)

PageView will say:

Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocols

I'll greatly appreciate any ideas.


Solution

  • Try using type erasure by casting every view to AnyView:

    var pageViewViewArray: [AnyView] = [AnyView(TestView()), AnyView(AnotherView()), AnyView(DifferentView())]
    

    Documentation here, and an example of using it here.