TabView,tabItem:选择运行代码或添加onTapGesture

时间:2020-09-22 23:04:59

标签: swift swiftui tabview tabitem

当我在tabview中选择一个标签时,我想运行一些代码。

假设:我想创建一个应用程序,其目的是:A)使用Tabview,B)严重混淆用户。为此,我将创建一个带有选项卡“一个”,“两个”和“三个”以及视图“一个”,“两个”和“三个”的应用程序。然后,在选择了第二选项卡时,我会改变视图“二”说“一个”代替。恶魔般的。

对此的常识性解决方案如下:

import SwiftUI

struct ContentView: View {
    @State private var two : String = "Two"
    var body: some View {
        TabView() {
          Text("One")
            .tabItem {
              Text("One")
            }
          Text("Two")
            .tabItem {
              Text(two)
            }
              .onTapGesture {
                print("Tapped!!")
                self.two = "One"
              }
          Text("Three")
            .tabItem {
              Text("Three")
            }
        }
    }
}

不幸的是,它的工作原理与普通应用完全相同,并且因为两个未更新(并且控制台中没有“已点击!”)而无法使用户感到困惑。

如何当TabItem的选择或分接运行代码?这可能是更新变量,运行动画或其他任何操作。

1 个答案:

答案 0 :(得分:6)

这是一个解决方案-您可以观察选项卡选择的变化并做出相应的反应。

通过Xcode 12 / iOS 14测试

import Combine   // << needed for Just publisher below

struct ContentView: View {
    @State private var two : String = "Two"
    @State private var selection: Int = 1

    var body: some View {
        TabView(selection: $selection) {
          Text("One")
            .tabItem {
              Text("One")
            }.tag(1)
          Text("Two")
            .tabItem {
              Text(two)
            }.tag(2)
          Text("Three")
            .tabItem {
              Text("Three")
            }.tag(3)
        }
  //      .onChange(selection) {          // << if SwiftUI 2.0 min spec
        .onReceive(Just(selection)) {
                 print("Tapped!!")
            if $0 == 2 {
                 self.two = "One"
            }
        }
    }
}