SwiftUI—如何通过AnyView返回任意类型的视图
2020-07-20 本文已影响0人
anny_4243
原文链接: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)))
}
}
}
