工具栏中带有分段控件的macOS SwiftUI应用选项卡视图


9

我正在尝试使用SwiftUI创建一个macOS应用程序。我需要一个TabView或类似的东西,但是当我使用TabView分段控件时,它不在macOS工具栏中。单击此处查看我想要的示例

我当前的代码是:

import SwiftUI

struct ContentView: View {
    var body: some View {
        TabView {
            Text("1")
                .tabItem {
                    Text("1")
            }
        }
    }
}

结果在这里作为图像

分段控件需要在工具栏而不是视图中。

谢谢。

Answers:


1

这是实现此目的的可能方法的简化演示。经过测试并与Xcode 11.2配合使用。

演示

1)准备窗口以具有所需的样式和背景 AppDelegate

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Create the SwiftUI view that provides the window contents.
    let contentView = ContentView()
        .edgesIgnoringSafeArea(.top)
        .frame(minWidth: 480, maxWidth: .infinity, minHeight: 300, maxHeight: .infinity)

    // Create the window and set the content view. 
    window = NSWindow(
        contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
        styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
        backing: .buffered, defer: false)
    window.center()
    window.titlebarAppearsTransparent = true
    window.titleVisibility = .hidden

    window.setFrameAutosaveName("Main Window")
    window.contentView = NSHostingView(rootView: contentView)
    window.makeKeyAndOrderFront(nil)
}

2)准备窗口内容视图以具有所需的行为

struct ContentView: View {
    private let tabs = ["Watch Now", "Movies", "TV Shows", "Kids", "Library"]
    @State private var selectedTab = 0
    var body: some View {
        VStack {
            HStack {
                Spacer()
                Picker("", selection: $selectedTab) {
                    ForEach(tabs.indices) { i in
                        Text(self.tabs[i]).tag(i)
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding(.top, 8)
                Spacer()
            }
            .padding(.horizontal, 100)
            Divider()
            GeometryReader { gp in
                VStack {
                    ChildTabView(title: self.tabs[self.selectedTab], index: self.selectedTab)
                }
            }
        }
    }
}

struct ChildTabView: View {
    var title: String
    var index: Int

    var body: some View {
        Text("\(title)")
    }
}

谢谢您的回答。我确实正在寻找类似于Apple应用程序的内容,即使在AppKit中也是如此。不过,您的回应表示赞赏。谢谢
NG235

我相信苹果在WWDC 2019上展示了SwiftUI Mac应用程序,工具栏中有分段控件。
NG235 20:51
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.