View我正在制作一個具有各種螢屏的應用程式,并且我想在一組視圖中收集所有符合的螢屏。在應用程式的主螢屏上,我想向所有螢屏標題顯示所有螢屏標題的串列NavigationLink。我遇到的問題是,如果我嘗試創建一個自定義視圖結構并擁有一個初始化給給定螢屏并回傳它的屬性。我不斷遇到問題,編譯器迫使我將變數更改為接受any View,而不僅僅是View或洗掉的型別some View。
struct Screen: View, Identifiable {
var id: String {
return title
}
let title: String
let destination: any View
var body: some View {
NavigationLink(destination: destination) { // Type 'any View' cannot conform to 'View'
Text(title)
}
}
}
這有效:
struct Screen<Content: View>: View, Identifiable {
var id: String {
return title
}
let title: String
let destination: Content
var body: some View {
NavigationLink(destination: destination) {
Text(title)
}
}
}
但是這種方法的問題是我不能將不同的螢屏放入一個陣列中,可以按如下方式修復:
struct AllScreens {
var screens: [any View] = []
init(){
let testScreen = Screen(title: "Charties", destination: SwiftChartsScreen())
let testScreen2 = Screen(title: "Test", destination: NavStackScreen())
screens = [testScreen, testScreen2]
}
}
但是當我嘗試訪問串列中的螢屏時,它無法在沒有型別轉換的情況下推斷出它是什么視圖。我試圖實作的最終結果是能夠傳入一系列螢屏并將其標題顯示在如下串列中。

目前我只能通過硬編碼串列元素來實作這一點,這很有效。
import SwiftUI
struct MainScreen: View {
let screens = AppScreens.allCases
let allScreens = AllScreens()
var body: some View {
NavigationStack() {
List() {
AppScreens.chartsScreen
AppScreens.navStackScreen
}
.navigationTitle("WWDC 22")
}
}
}
uj5u.com熱心網友回復:
SwiftUI 是資料驅動的回應式框架,而 Swift 是嚴格型別的語言,因此我們可以讓資料負責提供相應的視圖(現在與ViewBuilder 的幫助非常簡單)。
所以這里有一個方法。使用 Xcode 13 / iOS 15 測驗(NavigationView 或 NavigationStack - 這并不重要)
enum AllScreens: CaseIterable, Identifiable { // << type !!
case charts, navStack // << known variants
var id: Self { self }
@ViewBuilder var view: some View { // corresponding view !!
switch self {
case .charts:
Screen(title: "Charties", destination: SwiftChartsScreen())
case .navStack:
Screen(title: "Test", destination: NavStackScreen())
}
}
}
用法很明顯:
struct MainScreen: View {
var body: some View {
NavigationStack { // or `NavigationView` for backward compatibility
List(AllScreens.allCases) {
$0.view // << data knows its presenter
}
.navigationTitle("WWDC 22")
}
}
}
GitHub 上的測驗模塊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/489112.html
標籤:IOS 代码 迅捷 swiftui 列表 swiftui-导航链接
