Parchment icon indicating copy to clipboard operation
Parchment copied to clipboard

SwiftUI loading multiple views within PageView

Open ashleyevans opened this issue 3 years ago • 1 comments

Hi all

I've used Parchment in UIKit projects before with success but now trying it in SwiftUI and hitting a little roadblock. When trying to conditionally load a view per tab, I'm hitting the dreaded

Type '()' cannot conform to 'View'

when using a switch or if statement to conditionally load the view. Any pointers on how best to achieve the below?

PageView(options: pagingOptions, items: items) { item in
    switch item.index {
    case 0:
        FirstView()
    case 1:
        SecondView()
    case 2:
        ThirdView()
    case 3:
        FourthView()
    default:
        Text("Default")
    }
}

Sure it's something very simple I'm missing

Many thanks

ashleyevans avatar Dec 02 '21 11:12 ashleyevans

You can create a function that returns a view and place it inside the PageView.

@ViewBuilder
func page(atIndex index: Int) -> some View {
    switch item.index {
    case 0:
        FirstView()
    case 1:
        SecondView()
    case 2:
        ThirdView()
    case 3:
        FourthView()
    default:
        Text("Default")
    }
}

And use it like this:

PageView(options: pagingOptions, items: items) { item in
    func page(atIndex: item.index)
}

trevinwisaksana avatar Feb 18 '22 02:02 trevinwisaksana

There's a new version in beta now which should make this much nicer https://github.com/rechsteiner/Parchment/releases/tag/v4.0.0-beta. Let me know if you have any feedback 🙌

rechsteiner avatar Apr 02 '23 11:04 rechsteiner