SwiftUI 将两个子视图传递给 View [英] SwiftUI Pass two child views to View

查看:31
本文介绍了SwiftUI 将两个子视图传递给 View的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 @ViewBuilder 将两个视图作为视图的子视图传递.

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)))

            }
        }
    }

如何通过摆脱我的 FeedItem 类型来使这更通用.我希望这两个视图是两种不同的视图类型.

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.

推荐答案

这里是可能的变体.使用 Xcode 11.4/iOS 13.4 测试

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)))

            }
        }
    }
}

这篇关于SwiftUI 将两个子视图传递给 View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆