从事我的第一个 SwiftUI 项目。
在 UIKit 中微不足道,因为所有视图都是类。
现在,当我尝试创建一个返回受限于类型的视图的函数时:
protocol RootView : View {
func left() -> View // 1
func right() -> View // 2
}
func viewFor(_ i : Int) -> RootView { //3
}
1,2 & 3 抛出“协议视图只能用作通用约束.....”
我尝试了无数种组合(在 RootView、@ViewBuilder 等中使用关联类型)
保持简单,
我们如何从 SwiftUI 中的函数返回一个协议绑定的视图?
对不起,如果解决方案是基本的,一周前刚开始 SwiftUI
答案 0 :(得分:1)
你需要使用泛型,比如
protocol RootView : View {
associatedtype LeftView: View
associatedtype RightView: View
func left() -> LeftView // 1
func right() -> RightView // 2
}
func viewFor(_ i : Int) -> some RootView { // 3
// ... your concrete root view constructed here
}