如何在SwiftUI中使NavigationTitle打开一个选择器视图?

huangapple go评论108阅读模式
英文:

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:

如何在SwiftUI中使NavigationTitle打开一个选择器视图?

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)
    }
}

huangapple
  • 本文由 发表于 2023年7月20日 16:18:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定