Warm tip: This article is reproduced from serverfault.com, please click

swift-Swiftui TabBar:轻击当前选定选项卡的TabItem以重置视图的操作

(swift - Swiftui TabBar: Action for tapping TabItem of currently selected Tab to reset view)

发布于 2020-11-28 08:50:23

我正在使用的App基于TabBar,当我位于选项卡上时,我希望能够再次单击tabItem以重置视图,类似于twitter在其tabBar中的操作方式。

不过,我不知道该如何识别该动作。向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)
    }
  }
}

再次打开选项卡时,它不应自动重置(我已经在其他地方讨论过),但是再次点击tabItem时,它不会自动重置。

我在这里可能还缺少什么?

Questioner
matthias_code
Viewed
11
Asperi 2020-11-28 17:19:46

这是可能的解决方案-在TabView选择状态周围注入代理绑定,并在设置绑定值之前处理重复的制表符,如下所示。

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