簡體   English   中英

SwiftUI 不喜歡 switch?

[英]SwiftUI doesn't like switch?

為了遵循這個討論,我實施了Yurii Kotov的建議:

struct ContentView: View {

@State private var index = 0

@ViewBuilder
 var body: some View {
   if index == 0 {
       MainView()
   } else {
       LoginView()
   }
}

它工作正常。 但是,如果我嘗試使用 switch 語句:

    switch  index {
        case 0: MainView()
        case 1: LoginView()
        default:
            print("# error in switch")
        }

沒發生什么事。 沒有錯誤警報,但也根本沒有結果。 有人可以幫忙嗎?

我在默認情況下遇到了問題,我希望在“中斷”類型的情況下使開關變得詳盡無遺。 SwiftUI 需要某種類型的視圖,我發現

EmptyView()解決了這個問題。

還注意到這里EmptyView Discussion你“必須返回一些東西”

struct FigureListMenuItems: View {
    var showContextType: ShowContextEnum
    @Binding var isFavoriteSeries: Bool?

    var body: some View {
    
        Menu {
            switch showContextType {
            case .series:
                Button(action: { toggleFavoriteSeries() }) {
                    isFavoriteSeries! ?
                    Label("Favorite Series?", systemImage: "star.fill")
                        .foregroundColor(.yellow)
                    :
                    Label("Favorite Series?", systemImage: "star")
                        .foregroundColor(.yellow)
                }
            default: // <-- can use EmptyView() in this default too if you want
                Button(action: {}) {
                    Text("No menu items")
                }
            }
        } label: {
            switch showContextType {
            case .series:
                isFavoriteSeries! ?
                Image(systemName: "star.fill")
                    .foregroundColor(.yellow)
                :
                Image(systemName: "star")
                    .foregroundColor(.yellow)
            default:
                EmptyView()
            }
            Label("Menu", systemImage: "ellipsis.circle")
        }
    }

    private func toggleFavoriteSeries() {
        isFavoriteSeries?.toggle()
    }
}

開關的枚舉

enum ShowContextEnum: Int {
    case series = 1
    case whatIsNew = 2
    case allFigures = 3
}

正如@Sweeper 所說:您的if...elseswitch...case語句不相等。 主要思想是: body只是一個View 協議計算變量,它應該返回它的類型。 當然,您可以使用switch...case語句來實現。 在您的代碼片段中,錯誤在於default語句: body 不能返回() -> Void ,只有some View 所以你的代碼應該是這樣的:

struct ViewWithSwitchStatements: View {

    @State var option = 0

    var body: some View {

        switch option {
        case 1:
            return AnyView(Text("Option 1"))
        case 2:
            return AnyView(Text("Option 2"))
        default:
            return AnyView(Text("Wrong option!"))
        }

    }
}

但是你不能把它放到VStack或其他東西中,比如if...else語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM