SwiftUI:如何在 macOS 11 上设置工具栏的标题?
Posted
技术标签:
【中文标题】SwiftUI:如何在 macOS 11 上设置工具栏的标题?【英文标题】:SwiftUI: How to set the title for the toolbar on macOS 11? 【发布时间】:2020-10-14 19:21:16 【问题描述】:我有一个 SwiftUI 应用程序,它有两列和一个工具栏。我正在尝试模拟最新的 macOS 应用程序并以与 Mail 相同的方式使用工具栏,即选择一个侧边栏项目并将其显示为窗口的标题。
这是我的代码:
import SwiftUI
var listItems = ["Item 1", "Item 2", "Item 3", "Item 4"]
var secondItems = ["Second 1", "Second 2", "Second 3", "Second 4"]
struct ContentView: View
@State var select: String? = "Item 1"
var body: some View
VStack
NavigationView
List
ForEach((0..<listItems.count), id: \.self)
index in
NavigationLink(destination: SecondView(), tag: listItems[index], selection: $select)
Text(listItems[index])
.padding(.vertical, 2.0)
Spacer()
.frame(width:160)
.toolbar
Text("this is not the title")
Button(action: )
Label("Upload", systemImage: "square.and.arrow.up")
struct SecondView: View
var body: some View
NavigationView
List
ForEach((0..<secondItems.count), id: \.self)
index in
NavigationLink(destination: Text(secondItems[index]))
Text(secondItems[index])
.frame(height: 20)
.frame(width:150)
所以我得到一个这样的工具栏:
但是当我在第一个列表中选择一个项目时,如何在工具栏中设置窗口的标题?
【问题讨论】:
【参考方案1】:我是这样解决的:
import SwiftUI
var listItems = ["Item 1", "Item 2", "Item 3", "Item 4"]
var secondItems = ["Second 1", "Second 2", "Second 3", "Second 4"]
struct ContentView: View
@State var select: String? = "Item 1"
var body: some View
VStack
NavigationView
List
ForEach((0..<listItems.count), id: \.self)
index in
NavigationLink(destination: SecondView(), tag: listItems[index], selection: $select)
Text(listItems[index])
.frame(height: 20)
Spacer()
.listStyle(SidebarListStyle())
.toolbar
Text("this is not the title")
Button(action: )
Label("Upload", systemImage: "square.and.arrow.up")
.navigationTitle(select!)
.navigationSubtitle("\(listItems.count) records")
.navigationViewStyle(DoubleColumnNavigationViewStyle())
struct SecondView: View
var body: some View
NavigationView
List
ForEach((0..<secondItems.count), id: \.self)
index in
NavigationLink(destination: Text(secondItems[index]))
Text(secondItems[index])
.frame(height: 20)
【讨论】:
我不知道你做了什么来解决这个问题以上是关于SwiftUI:如何在 macOS 11 上设置工具栏的标题?的主要内容,如果未能解决你的问题,请参考以下文章
(SwiftUI, MacOS 11.0) 如何在 SecureTextFeild 中检测焦点?
SwiftUI TextField (MacOS) 的奇怪行为