简体   繁体   中英

SwiftUI TabView not rendering Preview Labels

I am developing a SwiftUI App for macOS.

However, i was not able to make TabView to render correctly in Preview Canvas and when using the view on a new Window.

struct DevView: View {
    
    @State var isOn = true
    
    var body: some View {
        TabView {
            Toggle(isOn: $isOn) {
                Text("Foo")
            }
            .toggleStyle(SwitchToggleStyle(tint: .green))
            .tabItem {
                Label("Foo", systemImage: "dot.square")
            }
            
            Text("Bar")
            .tabItem {
                Label("Bar", systemImage: "gear")
            }
            
        }.frame(width: 200, height:75)
    }
}

struct DevView_Previews: PreviewProvider {
    static var previews: some View {
        DevView()
    }
}

Why does this Code renders like this in Preview Canvas:

在此处输入图像描述

instead of correctly showing the tabs with labels:

在此处输入图像描述

For the record: XCode 13.2.1, BigSur 11.6.2

On MacOS SwiftUI does not render images in Tab labels: https://developer.apple.com/design/human-interface-guidelines/macos/windows-and-views/tab-views/

You have to go for a custom solution with Buttons. This seems to be tricky. The only way I got half way was the following.

在此处输入图像描述

This basically is a customizable ToolBar. To not have it in the title bar, you have to use.windowToolbarStyle(.expanded). Unfortunately the.windowToolbarStyle(.expanded) has to be directly on the WindowGroup:

@main
struct test_stack_macOsApp: App {
    var body: some Scene {
        WindowGroup {
            DevView()
                .toolbar(id: "myToolbar") {
                    ToolbarItem(id: "1", placement: .principal) {
                        Button {
                            // pass id to view
                        } label: {
                            Label("Foo", systemImage: "dot.square")
                        }
                    }
                    ToolbarItem(id: "2") {
                        Button {
                            // pass id to view
                        } label: {
                            Label("Bar", systemImage: "gear")
                        }
                    }
                }
                .navigationTitle("Foo")
        }
        .windowToolbarStyle(.expanded)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM