我通过线程在SwiftUI中成功实现了PageView:
How to implement PageView in SwiftUI?
只要所有视图都具有相同的结构,就可以通过数组传递多个视图,就像一个超级按钮一样。
PageView([TestView(), TestView()])
。
但是,我想传递不同的看法。
PageView([TestView(), AnotherView(), DifferentView()])
。
所有视图均为SwiftUI类型:
struct NAME : View { code }
当我尝试向数组添加其他结构时,出现以下错误消息:
var pageViewViewArray = [TestView(), AnotherView(), DifferentView()]
异构集合文字只能推断为“ [Any]”; 如果有意,请添加显式类型注释。
插入为[Any]
通过将其投射到:
var pageViewViewArray = [TestView(), AnotherView(), DifferentView()] as! [Any]
PageView(pageViewViewArray)
PageView会说:
协议类型“任何”都不能符合“视图”,因为只有具体类型才能符合协议
我将不胜感激任何想法。
答案 0 :(得分:3)
通过将每个视图投射到AnyView
来尝试使用类型擦除:
var pageViewViewArray: [AnyView] = [AnyView(TestView()), AnyView(AnotherView()), AnyView(DifferentView())]
答案 1 :(得分:1)
有一种更有效的方法,无需类型擦除。您应该创建一个通用视图,在其中注入一个枚举值,然后根据该值返回所需的视图。看看下面的例子:
/// The first type of a view that accepts and shows a number
struct ViewA: View {
let number: Int
var body: some View {
Text("\(number)")
}
}
/// The second type of a view that accepts and shows a string
struct ViewB: View {
let string: String
var body: some View {
Text(string)
}
}
/// An enum type used for dependency injection
enum ViewType {
case viewA(number: Int)
case viewB(string: String)
}
/// A common view which internally handles different kind of views based on injected enum value
struct CommonView: View {
let viewType: ViewType
var body: some View {
switch viewType {
case .viewA(let number):
ViewA(number: number)
case .viewB(let string):
ViewB(string: string)
}
}
}
// Views used for page view controller, that are now of same type:
var pageViewViewArray = [
CommonView(viewType: .viewA(number: 1)),
CommonView(viewType: .viewB(string: "Hello, World!"))
]