Reputation: 33
I have two reusable views, Ex1 and Ex2. I am trying to show one of them depends on a condition alternately but I could not it.
ContentvIew:
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")
}
}
ContentViewController :
import Foundation
class ContentViewController {
let a = Ex1()
let b = Ex2()
func getView (t: Bool) ->(Any){
if t {
return a
}
else {
return b
}
}
}
I think it is very simple but not for me, for now. Help for two things, please.
I want to understand this problem, and the solution.
Best way for alternate two view in a layout.
Thanks in advance.
Upvotes: 3
Views: 3088
Reputation: 23053
As the error suggests the return type specified in ContentViewController
's getView
method does not conform to the protocols.
In SwiftUI everything you specified in body{}
clause must be a type of View
if you do not know what kind of view available at runtime.
You can specify AnyView
type for unknown views.
So your error will be removed by changing the ContentViewController
's code.
class ContentViewController {
let a = Ex1()
let b = Ex2()
func getView (t: Bool) -> (AnyView) {
if t {
return AnyView(a)
}
else {
return AnyView(b)
}
}
}
Upvotes: 4