gpt4 book ai didi

SwiftUI - PageView - 在不同的 View 中传递

转载 作者:行者123 更新时间:2023-12-03 09:23:51 29 4
gpt4 key购买 nike

我通过线程在 SwiftUI 中成功实现了 PageView:
How to implement PageView in SwiftUI?

只要所有 View 都具有相同的结构,通过数组传递多个 View 就像一个魅力。PageView([TestView(), TestView()]) .
但是,我想传递不同的观点。PageView([TestView(), AnotherView(), DifferentView()]) .

所有 View 都是 SwiftUI 类型:struct NAME : View { code }
当我尝试向数组添加不同的结构时,我收到以下错误消息:

var pageViewViewArray = [TestView(), AnotherView(), DifferentView()]

Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional.
Insert' as [Any]



通过将其转换为:
var pageViewViewArray = [TestView(), AnotherView(), DifferentView()] as! [Any]
PageView(pageViewViewArray)

PageView 会说:

Protocol type 'Any' cannot conform to 'View' because only concrete types can conform to protocols



我将不胜感激任何想法。

最佳答案

通过将每个 View 强制转换为 AnyView 来尝试使用类型删除:

var pageViewViewArray: [AnyView] = [AnyView(TestView()), AnyView(AnotherView()), AnyView(DifferentView())]

文档 here ,以及使用它的示例 here .

关于SwiftUI - PageView - 在不同的 View 中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486867/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com