I have code like this
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))
}
}
It applies modifier withTabItem that should return some type TabItemView which contains tabItem and content in properties and renders just content.
Then in other place in code I would like to cast View into this TabItemView to access tabItem property from it like below:
if let tabbed = views.0 as? TabItemView {
tabItems.append(tabbed.tabItem())
}
But this casting is not possible.
UPDATE
I've changed it this way
var body: some View {
MenuView {
Page1()
Page2()
.menuTabItem(tag: 1) {
TabItemView(systemImage: "person", title: "Tab 2")
}
And the new implementation of this ViewModifier is very simple, like this
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
}
}
But the problem is that I can only use it directly inside MenuView. The usage of this modifier inside Page1(), causes that view is hidden under Page1, and then inside implementation of MenuView I cannot access this modifier with above casting, there is also no reference to this modifier chain.