【问题标题】:Custom TabView navigation in SwiftUISwiftUI 中的自定义 TabView 导航
【发布时间】:2020-12-09 09:06:58
【问题描述】:

我正在尝试为我的应用创建自定义 TabView。我已经按照这个教程进行操作,但是我无法根据按下的按钮来改变视图。下面是我的 TabView 上显示的按钮的代码。按下此按钮时,我希望显示 HomeView 以及按下 Account 按钮以显示 AccountView etyc 等。

我想知道如何解决这个问题。我曾尝试使用 NavLinks 但没有运气,因为我无法使用动画。

我是 SwiftUI 的新手,正在努力学习。

谢谢

Button{
            
            withAnimation{
                index = 0
            }
            
        }
        label: {
                
            HStack(spacing: 8){
                
                Image(systemName: "house.fill")
                    .foregroundColor(index == 0 ? .white : Color.black.opacity(0.35))
                    .padding(10)
                    .background(index == 0 ? Color("BrightGreen") : Color.clear)
                    .cornerRadius(8)
                
                Text(index == 0 ? "Home" : "")
                    .foregroundColor(.black)
            }
        }

【问题讨论】:

    标签: ios swift swiftui swiftui-tabview


    【解决方案1】:

    您可以使用@State 变量来决定应该向用户显示哪个视图。然后根据点击的按钮设置该变量的值。我已经编写了非常简单的代码来展示这个想法。

    // Views to show
    struct HomeView: View {
      var body: some View {
        Text("Home View")
      }
    }
    
    struct AccountView: View {
      var body: some View {
        Text("Account View")
      }
    }
    
    // Enum containing views available in tabbar
    enum ViewToDisplay {
      case home
      case account
    }
    
    struct ContentView: View {
      @State var currentView: ViewToDisplay = .home
      var body: some View {
        VStack {
          switch currentView{
          case .home:
            HomeView()
            
          case .account:
            AccountView()
          }
          Spacer()
          // Tabbar buttons
          HStack {
            Button(action: { currentView = .home }) { Text("Home") }
            Button(action: { currentView = .account }) { Text("Account") }
          }
        }
      }
    }
    

    它是这样工作的:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 2020-11-06
      • 2019-06-15
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多