美文网首页
SwiftUI—如何通过AnyView返回任意类型的视图

SwiftUI—如何通过AnyView返回任意类型的视图

作者: anny_4243 | 来源:发表于2020-07-20 15:31 被阅读0次

原文链接:https://github.com/fzhlee/SwiftUI-Guide#-%E7%AC%AC8%E8%8A%82anyview-

示例代码:

struct ContentView : View {
    
    private var randomBool = Bool.random() //用于判断显示哪一个视图,它的值是一个随机的布尔值
    
//    var body: some View {
//        Group {
//            if randomBool {
//                Text("Hi, you get the gift.")
//                    .font(.system(size: 32))
//            } else {
//                Text("Sorry, you miss the gift.")
//                    .font(.system(size: 32))
//            }
//        }
//    }
    
//    var body: some View {
//        if randomBool {
//            return Text("Hi, you get the gift.")
//                .font(.system(size: 32))
//        } else {
//            return Text("Sorry, you miss the gift.")
//                .font(.system(size: 32))
//        }
//    }
    
    var body: AnyView {
        if randomBool {
            return AnyView(Image(systemName: "star.fill").font(.system(size: 72)))
        } else {
            return AnyView(Text("Sorry, you miss the gift.").font(.system(size: 32)))
        }
    }
}

相关文章

网友评论

      本文标题:SwiftUI—如何通过AnyView返回任意类型的视图

      本文链接:https://www.haomeiwen.com/subject/jmxykktx.html