【发布时间】:2025-12-20 20:10:12
【问题描述】:
我有两个可重用的视图,Ex1 和 Ex2。我试图展示其中一个交替依赖于一个条件,但我做不到。
内容视图:
struct ContentView: View {
@State var selector = false
var cvc = ContentViewController()
var body: some View {
ZStack { // ERROR: Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocols
cvc.getView(t: selector)
Button(action: {
self.selector.toggle()
print(self.selector)
}) {
Text("Button")
}
}
}
}
Ex1:
import SwiftUI
struct Ex1: View {
var body: some View {
Text("Ex 1")
}
}
Ex2:
import SwiftUI
struct Ex2: View {
var body: some View {
Text("Ex 2")
}
}
内容视图控制器:
import Foundation
class ContentViewController {
let a = Ex1()
let b = Ex2()
func getView (t: Bool) ->(Any){
if t {
return a
}
else {
return b
}
}
}
我认为这很简单,但现在对我来说不是。请帮忙做两件事。
我想了解这个问题,以及解决方案。
在布局中交替使用两个视图的最佳方式。
提前致谢。
【问题讨论】: