简体   繁体   English

SwiftUI:点击手势切换视图

[英]SwiftUI: On tap gesture switches views

I have the following simplified code in a project using XCode 13.2.我在使用 XCode 13.2 的项目中有以下简化代码。 The intended functionality is to have 2 tabs ( Tab1 and Tab2 ), and the user is able to tap the screen on Tab2 to toggle the background from red to green.预期的功能是有 2 个选项卡( Tab1Tab2 ),用户可以点击Tab2上的屏幕以将背景从红色切换为绿色。

Instead, however, when Tab2 is clicked, the screen displays tab 1, instead of Tab2 with the changed color.但是,当单击Tab2时,屏幕会显示选项卡 1,而不是更改颜色的Tab2 I'm wondering why the app goes to Tab1 when Tab2 is tapped.我想知道为什么当点击Tab2时应用程序会转到Tab1

There are no NavigationLinks or actions that make the user go to Tab1 .没有使用户 go 到Tab1的 NavigationLinks 或操作。 My only thought is that maybe the app is rebuilding when Tab2 is clicked, which is why it goes back to the first tab?我唯一的想法是单击Tab2时可能正在重建应用程序,这就是为什么它会返回到第一个选项卡? If so, are there any good workarounds for this?如果是这样,有什么好的解决方法吗?

Note : the color still changes on Tab2 , but not before the app switches to Tab1 .注意:颜色在Tab2上仍然会发生变化,但在应用程序切换到Tab1之前不会发生变化。


struct ContentView: View {
    
    var body: some View {
        TabView {
            Tab1()
                .tabItem {
                    Text("Tab 1")
                }
            Tab2()
                .tabItem {
                    Text("Tab 2")
                }
        }
    }
}

struct Tab1: View {
    var body: some View {
        Text("Tab 1")
    }
}

struct Tab2: View {
    @State var isRed: Bool = false
    
    var body: some View {
        if !isRed {
            Color.green
                .onTapGesture {
                    isRed = true
                }
        } else {
            Color.red
                .onTapGesture {
                    isRed = false
                }
        }
    }
}

I have noticed that using if/else in that way causes strange behavior.我注意到以这种方式使用 if/else 会导致奇怪的行为。 Refactor Tab2 as shown below and it should work as expected.重构 Tab2 如下所示,它应该可以按预期工作。

struct Tab2: View {
@State var isRed: Bool = false

var body: some View {
    ZStack {
        Color.red
        Color.green
            .opacity(isRed ? 0 : 1)
    }
    .onTapGesture {
        isRed.toggle()
    }
}

} }

The reason why tapping on Tab2 causes it to jump back to Tab1 is that the structural identity of Tab2 changes whenever you tap on it causing swiftUI to reload the body.点击 Tab2 会导致它跳回 Tab1 的原因是,每当您点击 Tab2 时,它的结构标识都会发生变化,导致 swiftUI 重新加载主体。 See the explanation here .请参阅此处的说明。 A simple fix to the example you have above would be to wrap the entire body in a ZStack对上面示例的一个简单修复是将整个主体包裹在ZStack

var body: some View {
  ZStack {
    if !isRed {
      Color.green
        .onTapGesture {
          isRed = true
        }
    } else {
      Color.red
        .onTapGesture {
          isRed = false
        }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM