对于 MacOS,我将其添加到 ContentView 中的主 VStack 中,当我获取文件名时,我的工具栏卡在右侧。
.onAppear {
if let window = NSApplication.shared.windows.first {
window.title = "fileName"
}
}
我知道我的工具栏已正确定义,因为当我将此行添加到 onAppear 时,我的工具栏完全居中。
window.titleVisibility = .hidden
默认文件名区域似乎有一个巨大的 Spacer,将标题栏空间划分为 1/2。我从默认的 SwiftUI 项目开始我的项目。有没有办法去掉默认区域那个巨大的Spacer?
编辑-1
struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
ToolbarView( dm )
.navigationTitle("fileNamexxx")
...
如果我设置 window.titleVisibility = .hidden,我会得到“无文件名”且工具栏正确居中:
如果我不隐藏标题,我会得到这个:
我需要将我的工具集放在标题栏的中间,因为它位于另一个居中的按钮栏上方。
编辑2:
import SwiftUI
struct ContentView: View {
@State private var fileName = "Untitled"
var body: some View {
VStack {
Text("Your Content Here")
.padding()
}
.frame(minWidth: 200, minHeight: 100)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
.overlay(
CustomTitleBar(fileName: $fileName)
.frame(height: 30)
.background(Color.gray)
.edgesIgnoringSafeArea(.top)
)
.onAppear {
if let window = NSApplication.shared.windows.first {
window.title = fileName
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
}
}
}
}
struct CustomTitleBar: View {
@Binding var fileName: String
var body: some View {
HStack {
Text(fileName)
.foregroundColor(.white)
.padding(.leading, 8)
Spacer()
}
}
}
使用
navigationDocument
修饰符将文档名称和代理图标放在标题栏中。
使用
ToolbarItemGroup(placement: principal) { ... }
将项目放置在工具栏的中心(空间允许)。
代码:
struct ContentView: View {
@Binding var tool: Tool
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
.navigationDocument(URL(fileURLWithPath: "/tmp/Untitled"))
.toolbar {
ToolbarItemGroup(placement: .principal) {
Picker("Tools", selection: $tool) {
ForEach(Tool.allCases) {
Label($0.name, systemImage: $0.systemImage)
}
}
.pickerStyle(.inline)
}
}
.buttonStyle(.accessoryBar)
.frame(minWidth: 600, minHeight: 300)
}
}
enum Tool: Hashable, Identifiable, CaseIterable {
case select
case text
case line
case circle
case square
var id: Self { self }
var name: LocalizedStringKey {
return switch self {
case .select: "Select"
case .text: "Text"
case .line: "Line"
case .circle: "Circle"
case .square: "Square"
}
}
var systemImage: String {
return switch self {
case .select: "cursorarrow"
case .text: "textformat"
case .line: "line.diagonal"
case .circle: "circle"
case .square: "square"
}
}
var key: KeyEquivalent? {
return switch self {
case .select: "a"
case .text: "t"
case .line: "l"
case .circle: "c"
case .square: "s"
}
}
}
@main
struct testApp: App {
@State var tool: Tool = .select
var body: some Scene {
WindowGroup {
ContentView(tool: $tool)
}
.commands {
CommandMenu("Tools") {
ForEach(Tool.allCases) { candidate in
Toggle(isOn: .init(
get: { tool == candidate },
set: { _ in tool = candidate }
)) {
Text(candidate.name)
}
.keyboardShortcut(candidate.key.map { KeyboardShortcut($0, modifiers: []) })
}
}
}
}
}