我有这样的代码
import SwiftUI
struct TabItemModifier<TabItem>: ViewModifier where TabItem: View {
var tabItem: () -> TabItem
func body(content: Content) -> some View {
return TabItemView(tabItem: tabItem, content: content)
}
}
struct TabItemView<TabItem, Content> : View where Content: View, TabItem : View {
var tabItem: () -> TabItem
var content: Content
var body: some View {
content
}
}
extension View {
func withTabItem<V>(@ViewBuilder _ label: @escaping () -> V) -> some View where V: View{
ModifiedContent(content: self, modifier: TabItemModifier(tabItem: label))
}
}
它应用修饰符withTabItem,该修饰符应该返回某种类型的TabItemView,该类型在属性中包含tabItem和内容并仅呈现内容。
然后在代码中的其他位置,我想将 View 转换到此 TabItemView 中以从中访问 tabItem 属性,如下所示:
if let tabbed = views.0 as? TabItemView {
tabItems.append(tabbed.tabItem())
}
但是这种类型转换是不可能的。
更新
我已经改成这样了
var body: some View {
MenuView {
Page1()
Page2()
.menuTabItem(tag: 1) {
TabItemView(systemImage: "person", title: "Tab 2")
}
这个ViewModifier的新实现非常简单,就像这样
func menuTabItem<T>(tag: Int, @ViewBuilder _ tabItem: @escaping () -> T) -> some View
where T: View {
ModifiedContent(content: AnyView(self),
modifier: Click5MenuItemModifier(
tag: tag,
menuItem: nil,
tabItem: AnyView(tabItem())
)
)
}
struct MenuItemModifier: ViewModifier {
var tag: Int
var menuItem: AnyView?
var tabItem: AnyView?
func body(content: Content) -> some View {
return content
}
}
但问题是我只能直接在MenuView中使用它。在 Page1() 中使用此修饰符,导致 View 隐藏在 Page1 下,然后在 MenuView 的实现中我无法通过上述转换访问此修饰符,还有没有对此修饰符链的引用。
最佳答案
TabItemView
是一个具有两个关联类型的结构。使用时必须指定具体类型。像... as? TabItemView<Text, Color>
。但是,不可能指定不透明类型( View
)。所以我的建议是:
更改TabItemView
的content
至AnyView
并保留tabItem
的类型与 tabItems
相同的类型。
关于swift - 如何解决 Swift 泛型类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59030424/