swift - 在导航栏中显示不同标题的问题
问题描述
在我的代码中,我有这个:
var body: some View {
NavigationView {
VStack(spacing: 0) {
ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 18) {
ScrollView(.horizontal, showsIndicators: false){
HStack(spacing: 20){
Text("teste")
.frame(height: 180)
.frame(width: 330)
.background(Color.blue)
.cornerRadius(15)
Text("teste")
.frame(height: 180)
.frame(width: 330)
.background(Color.green)
.cornerRadius(15)
Text("teste")
.frame(height: 180)
.frame(width: 330)
.background(Color.pink)
.cornerRadius(15)
}.padding(.horizontal, 12)
}
ForEach(specialtyList, id: \.type){ specialty in
NavigationLink (destination: SearchBar(item: specialty)){
VStack(spacing: 18) {
HStack{
Text(specialty.type).foregroundColor(.white)
specialty.image
.renderingMode(.original)
.resizable()
.frame(width: 35, height: 35)
}.frame(minWidth: 0, idealWidth: 350, maxWidth: .infinity)
.frame(height: 100)
}
}.padding(.horizontal)
.background(specialty.color).cornerRadius(45)
}.padding(.horizontal)
}
.padding(.top)
.padding(.bottom)
}
}.navigationBarTitle("Buscar")
}.accentColor(.black)
}
我希望根据 ForEach 中按下的按钮,下一个视图的标题是按钮的名称。现在,每个按钮中显示的名称是“Buscar”,我试图在 ForEach 之后和 NavigationLink 之前实现一个 NavigationView,但 ForEach 的洞消失了。基本上,我希望按下的 Text(specialty.type) 是导航栏后退按钮的名称。有任何想法吗?
解决方案
这是一个可能的方法的演示 - 想法是在导航链接激活时更改导航栏标题并在后面重置。
使用 Xcode 12 / iOS 14 准备和测试的演示
struct DemoView: View {
@State private var barTitle = ""
@State private var selectedType = ""
@State private var isActive = false
let types = ["Type1", "Type2", "Type3"]
var body: some View {
NavigationView {
VStack {
ForEach(types, id: \.self) { type in
Button(type) {
self.isActive = true
self.selectedType = type
self.barTitle = type // comment for variant 2
}
}
}
.background(
NavigationLink(destination:
Text(selectedType)
// .onAppear { self.barTitle = self.selectedType } // variant 2
, isActive: $isActive) { EmptyView() }
)
.navigationBarTitle(barTitle)
.onAppear {
self.barTitle = "Buscar"
}
}
}
}
推荐阅读
- laravel - 使用 Laravel 发送邮件
- arrays - 优化 4D 张量旋转
- java - 参数索引超出范围 (0 < 1)
- prolog - Prolog:使用附加约束安排开始时间
- javascript - 如何让 VS Code Intellisense 识别 JSDoc 注解?
- typescript - 使用打字稿获取羽毛聊天教程的错误消息“错误:必须向'users.get'方法提供一个ID”
- vue.js - Vue-CLI 和 Visual Studio Code 格式冲突
- authentication - 独立 Blazor WebAssembly 身份验证非常慢
- java - FlowLayout 使标签居中?
- apache-spark - 无法使用 spark 将结果写入 kafka 主题