[英]How to workaround Swift generic type casting
我有這樣的代碼
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() 中使用此修飾符,導致視圖隱藏在 Page1 下,然后在 MenuView 的實現中,我無法通過上述轉換訪問此修飾符,也沒有對此修飾符鏈的引用。
TabItemView
是一個有兩個關聯類型的結構體。 使用時必須指定具體類型。 像…… as? TabItemView<Text, Color>
as? TabItemView<Text, Color>
。 但是,無法指定不透明類型( View
)。 所以我的建議是:
更改TabItemView
的content
,以AnyView
和保持tabItem
的類型是一樣tabItems
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.