英文:
How can I make a NavigationTitle in SwiftUI open a picker view?
问题
.navigationTitle($titleString)
可以绑定字符串到导航标题,但是否可以将其绑定到枚举以获取选择器视图?
(这不起作用,顺便说一下):
enum LibraryViewType: String, CaseIterable {
case albums, songs, artists
}
...
@State private var viewType: LibraryViewType = .albums
...
.navigationTitle($viewType)
英文:
I understand that you can bind a string to the navigation title like:
.navigationTitle($titleString)
and you get:
and this will allow you to rename it,
but is there a way to bind this to an enum to get a picker view?
(this doesn't work btw) :
enum LibraryViewType: String, CaseIterable {
case albums, songs, artists
}
...
@State private var viewType: LibraryViewType = .albums
...
.navigationTitle($viewType)
答案1
得分: 3
这是您应该使用 ToolbarTitleMenu
的地方。这是在您点击标题旁边的向下箭头时显示的菜单。您可以将选择器放在那里,并将标题设置为当前选择的枚举值的字符串表示形式。
@State var type = LibraryViewType.albums
var body: some View {
NavigationStack {
Color.white // 用于放置工具栏的虚拟视图
.toolbar {
ToolbarTitleMenu {
Picker("Picker", selection: $type) {
ForEach(LibraryViewType.allCases, id: \.self) { item in
Text(item.rawValue)
}
}
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(type.rawValue)
}
}
英文:
This is where you should use ToolbarTitleMenu
. That is the menu that is displayed when you tap the down-arrow next to the title. You can put your picker there, and set the title to a string representation of the currently selected enum value.
@State var type = LibraryViewType.albums
var body: some View {
NavigationStack {
Color.white // dummy view to put a toolbar on
.toolbar {
ToolbarTitleMenu {
Picker("Picker", selection: $type) {
ForEach(LibraryViewType.allCases, id: \.self) { item in
Text(item.rawValue)
}
}
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(type.rawValue)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论