Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Pass two child views to View

Tags:

swift

swiftui

I am trying to pass two views as childs of a View, using @ViewBuilder.

I need to be able to know which one is the first one and which one is the second one, as I want to show one or the other depending on some state.

I was able to make this work in a non generic manner, meaning that I explicitly give the types of the child views.

struct FlippableView<Content: View>: View {
    @State private var flipped = false
    @State private var degrees = 0.0

    var frontCard: FeedItem
    var backCard: FeedItem

    @inlinable public init(@ViewBuilder content: () -> Content) {
        var t = content() as! TupleView<(FeedItem, FeedItem)>
        self.frontCard = t.value.0
        self.backCard = t.value.1
    }

    var body: some View {
        return Group() {
            if self.degrees < 90 {
                self.frontCard
            } else {
                self.backCard
                    .rotation3DEffect(Angle(degrees: 180), axis: (x: CGFloat(0), y: CGFloat(10), z: CGFloat(0)))

            }
        }
    }

How can I make this more generic, by getting rid of my FeedItem types. I would like the two views to be two different View types.

like image 707
Scaraux Avatar asked Sep 18 '25 04:09

Scaraux


1 Answers

Here is possible variant. Tested with Xcode 11.4 / iOS 13.4

struct FlippableView<V1: View, V2: View>: View {
    @State private var flipped = false
    @State private var degrees = 0.0

    var frontCard: V1
    var backCard: V2

    @inlinable public init(@ViewBuilder content: () -> TupleView<(V1, V2)>) {
        let t = content()
        self.frontCard = t.value.0
        self.backCard = t.value.1
    }

    var body: some View {
        return Group() {
            if self.degrees < 90 {
                self.frontCard
            } else {
                self.backCard
                    .rotation3DEffect(Angle(degrees: 180), axis: (x: CGFloat(0), y: CGFloat(10), z: CGFloat(0)))

            }
        }
    }
}
like image 127
Asperi Avatar answered Sep 19 '25 22:09

Asperi