【问题标题】:SwiftUI alternate views - Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocolsSwiftUI 备用视图 - 协议类型“任何”不能符合“视图”,因为只有具体类型才能符合协议
【发布时间】: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
        }
    }
}

我认为这很简单,但现在对我来说不是。请帮忙做两件事。

  1. 我想了解这个问题,以及解决方案。

  2. 在布局中交替使用两个视图的最佳方式。

提前致谢。

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    由于错误表明ContentViewControllergetView 方法中指定的返回类型不符合协议。

    在 SwiftUI 中,如果您不知道运行时可用的视图类型,您在 body{} 子句中指定的所有内容都必须是 View 类型。

    您可以为未知视图指定AnyView 类型。

    因此,您的错误将通过更改ContentViewController 的代码来消除。

    class ContentViewController {
    
        let a = Ex1()
        let b = Ex2()
    
        func getView (t: Bool) -> (AnyView) {
            if t {
                return AnyView(a)
            }
            else {
                return AnyView(b)
            }
        }
    }
    

    【讨论】:

    • 谢谢@Kampai。有效。 (添加“导入 SwiftUI”后)。