问题描述
我有一个包含 TabView 的 ContentView.swift.
I have a ContentView.swift which contains a TabView.
View1 中有一个带有一些子视图的 NavigationView.View2 只是一个 View.
View1 has a NavigationView in it with some childViews.View2 is just a single View.
我想在按下第一个 tabItem 时执行一些操作(总是返回到 View1,即使在 View1 的 childView 中).即使它已经是活动的tabItem.
I would like to perform some action (always return to View1, even when being in a childView of View1), when the first tabItem is pressed. Even if it is already the active tabItem.
我尝试了如下所示的 onTapGesture,它似乎没有任何作用.在.tag(0)"之前添加它也没有改变任何东西:
I tried onTapGesture as seen below, which didn't seem to do anything. Adding it right before ".tag(0)" didn't change anything, either:
TabView {
View1()
.onTapGesture {
print("Test")
}
.tabItem {
Image(systemName: "doc.plaintext")
.font(.system(size: 25))
Text("View1")
}.tag(0)
View2()
.tabItem {
Image(systemName: "person.crop.circle")
.font(.system(size: 25))
Text("View2")
}.tag(1)
推荐答案
这是可能的方法.使用 Xcode 11.4/iOS 13.4 测试
Here is possible approach. Tested with Xcode 11.4 / iOS 13.4
struct TestTabSelectionAction: View {
@State private var selectedTab = 0
var body: some View {
let selection = Binding<Int>(
get: { self.selectedTab },
set: { self.selectedTab = $0
print("Pressed tab: ($0)")
if $0 == 0 {
// <<< your action here !!
}
})
return TabView(selection: selection) {
View1()
.tabItem {
Image(systemName: "doc.plaintext")
.font(.system(size: 25))
Text("View1")
}.tag(0)
View2()
.tabItem {
Image(systemName: "person.crop.circle")
.font(.system(size: 25))
Text("View2")
}.tag(1)
}
}
}
这篇关于TabView (SwiftUI):在已经激活的 tabItem 上响应 onTab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!