使用SwiftUI展平TupleViews [英] Flatten TupleViews using SwiftUI

查看:42
本文介绍了使用SwiftUI展平TupleViews的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,SwiftUI已于本周发布,所以我们所有人都是n00b,但是...我有以下测试代码:

Ok, SwiftUI was released this week so we're all n00bs but... I have the following test code:

var body: some View {
    switch shape {
    case .oneCircle:
        return ZStack {
            Circle().fill(Color.red)
        }
    case .twoCircles:
        return ZStack {
            Circle().fill(Color.green)
            Circle().fill(Color.blue)
        }
    }
}

会产生以下错误:

函数声明了不透明的返回类型,但其主体中的return语句没有匹配的基础类型

发生这种情况是因为第一个ZStack就是这种类型:

This happens because the first ZStack is this type:

ZStack<ShapeView<Circle, Color>>

第二种是这种类型:

ZStack<TupleView<(ShapeView<Circle, Color>, ShapeView<Circle, Color>)>>

如何在SwiftUI中处理此问题?它们可以以某种方式展平还是可以被制成符合同一类型.

How do I deal with this in SwiftUI? Can they be flattened somehow or be made to conform to the same type.

推荐答案

解决此问题的一种方法是使用橡皮擦 AnyView :

One way to fix this is to use the type eraser AnyView:

var body: some View {
    switch shape {
    case .oneCircle:
        return AnyView(ZStack {
            Circle().fill(Color.red)
        })
    case .twoCircles:
        return AnyView(ZStack {
            Circle().fill(Color.green)
            Circle().fill(Color.blue)
        })
    }
}

这篇关于使用SwiftUI展平TupleViews的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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