今天在做一个搜索页面,如图所示: 右上角时钟按钮点进去是历史搜索词: 我原本打算直接在navigationBarItems中使用NavigationLink 跳转,点击其中一个历史搜索词后自动返回并替换搜索框内容:
.navigationBarItems(trailing:
HStack{
if(historys.count > 0){
NavigationLink(destination: historyPanel,isActive:$showHistory) {
Label("", systemImage: "clock.arrow.circlepath")
}
}
NavigationLink(destination: ScanQR(targetCollection: $targetCollection, targetTodo: $targetTodo, isCollection: $isCollection, isTodo: $isTodo)) {
Image(systemName: "qrcode.viewfinder").font(.title3)
}
})
var historyPanel: some View{
List{
ForEach(historys,id:\.self){ history in
Button(action: {pickHistory(history: history)}) {
Text(history)
.padding(6)
}
}
}
.navigationBarTitle("History")
.navigationBarItems(trailing:
Button(action: ClearHistory) {
Text("Clear")
}
)
}
func pickHistory(history:String) {
searchStr = history
refresh()
showHistory = false
}
但是点击后虽然搜索框的内容被替换了,isActive 所引用的Bool值也是false的, 但是没有自动返回。 查阅网友经验后无果,于是我尝试使用0高度隐藏NavigationLink + Button触发的方式:
在任意某个地方放入0高度NavigationLink:
NavigationLink(destination: historyPanel,isActive:$showHistory) {
Label("", systemImage: "clock.arrow.circlepath")
}.frame(height:0)
然后将navigationBarItems中的内容替换如下:
HStack{
if(historys.count > 0){
Button(action: {showHistory.toggle()}) {
Label("", systemImage: "clock.arrow.circlepath")
}
}
NavigationLink(destination: ScanQR(targetCollection: $targetCollection, targetTodo: $targetTodo, isCollection: $isCollection, isTodo: $isTodo)) {
Image(systemName: "qrcode.viewfinder").font(.title3)
}
}
这时候成功触发了返回,我猜测应该是NavigationLink 直接点击的话,系统会忽略 isActive 属性,导致变量无效,如果全程使用变量控制,就能够触发了。
|