[英]Swiftui TabBar: Action for tapping TabItem of currently selected Tab to reset view
The App I am working on is based around a TabBar, and when I am on a tab I want to be able to click the tabItem again to reset the view, similar to how twitter does it in their tabBar.我正在开发的应用程序基于 TabBar,当我在选项卡上时,我希望能够再次单击 tabItem 以重置视图,类似于 twitter 在其 tabBar 中的操作方式。
I do not know how to recognize that action though.我不知道如何识别该动作。 Adding a button to the TabItem is not working, addidng a tapGesture modifier isn't either, and I can't think of anything else I could try.
向 TabItem 添加按钮不起作用,添加一个 tapGesture 修饰符也不起作用,我想不出我可以尝试的其他任何东西。
struct ContentView: View {
var body: some View {
TabView() {
Text("Tab 1")
.tabItem {
Image(systemName: "star")
.onTapGesture {
print("Hello!")
}
Text("One")
}
.tag(0)
Text("Tab 2")
.tabItem {
Button(action: {
print("Hello!")
}, label: {
Image(systemName: "star.fill")
})
}
.tag(1)
}
}
}
It should't automatically reset when opening the tab again, which I have seen discussed elsewhere, but when tapping the tabItem again.它不应该在再次打开选项卡时自动重置,我在其他地方已经看到过,但是在再次点击 tabItem 时。
What other things am I possibly missing here?我在这里可能还缺少什么其他东西?
Here is possible solution - inject proxy binding around TabView
selection state and handle repeated tab tapped before bound value set, like below.这是可能的解决方案 - 在
TabView
选择 state 周围注入代理绑定并处理在绑定值设置之前点击的重复选项卡,如下所示。
Tested with Xcode 12.1 / iOS 14.1使用 Xcode 12.1 / iOS 14.1 测试
struct ContentView: View {
@State private var selection = 0
var handler: Binding<Int> { Binding(
get: { self.selection },
set: {
if $0 == self.selection {
print("Reset here!!")
}
self.selection = $0
}
)}
var body: some View {
TabView(selection: handler) {
Text("Tab 1")
.tabItem {
Image(systemName: "star")
Text("One")
}
.tag(0)
Text("Tab 2")
.tabItem {
Image(systemName: "star.fill")
}
.tag(1)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.