【问题标题】:TabView, tabItem: running code on selection or adding an onTapGestureTabView、tabItem:在选择时运行代码或添加 onTapGesture
【发布时间】:2020-09-22 23:04:59
【问题描述】:

当我在 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")
            }
        }
    }
}

不幸的是,它的工作原理与普通应用完全一样,并且无法混淆用户,因为其中两个没有更新(并且控制台中没有“Tapped!”)。

如何在选择或点击 tabItem 时运行代码?这可能是更新变量、运行动画或其他任何事情。

【问题讨论】:

    标签: swift swiftui tabview tabitem


    【解决方案1】:

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

    使用 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"
                }
            }
        }
    }
    

    【讨论】:

    • 谢谢!这是完美的。
    • 如何用.onTapGesture 计算tabItem
    • 谢谢!我收到了多个打印语句,内容如下:LazyHStack { TabView(selection: $annotationIndex) { ForEach(filteredListings.indices, id: \.self) { index in Text("FOO") } } .onReceive(Just(annotationIndex)) { index in print("select \(index)") } .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never)) }
    • 这似乎是正确的方法,但我无法让它为我工作。 “Tapped”在视图加载时打印一次,但在更改选项卡时不会再次打印
    猜你喜欢
    • 2020-04-20
    • 2012-05-14
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2010-10-19
    相关资源
    最近更新 更多