【问题标题】:Button not changing view in SwiftUI按钮不改变 SwiftUI 中的视图
【发布时间】:2020-02-04 02:02:03
【问题描述】:

所以在我的 ContentView.swift 中,我有以下代码:

import SwiftUI

extension UIScreen{
   static let screenWidth = UIScreen.main.bounds.size.width
   static let screenHeight = UIScreen.main.bounds.size.height
   static let screenSize = UIScreen.main.bounds.size
}

struct ContentView: View {
    @State var Direction: Int = 0
    @State var ButtonsShowing: Bool = true
    @State var View: Int = 0

    func MoveLeft() {
        if ButtonsShowing == true {
            ButtonsShowing = false
        }
    }

    func MoveRight() {
        if ButtonsShowing == true {
            ButtonsShowing = false
        }
        Direction = 1
    }

    var body: some View {
        ZStack {
            Image("Space").resizable()
                .frame(width: UIScreen.screenWidth, height: UIScreen.screenHeight + 50)
                .edgesIgnoringSafeArea(.all)

            VStack {
                HStack {
                    Button(action: MoveLeft) {
                        if ButtonsShowing == true {
                            NavigationLink(destination: Playing()) {
                                Image("LeftClick")
                                    .frame(width: UIScreen.screenWidth / 2, height: UIScreen.screenHeight)
                            }

                        }
                    }

                    Spacer()

                    Button(action: MoveRight) {
                        if ButtonsShowing == true {
                            Image("RightClick")
                                .frame(width: UIScreen.screenWidth / 2, height: UIScreen.screenHeight)
                        }
                    }
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

我得到了这个预览: Preview of button with NavigationLink

如果您看向我的 LeftClick 按钮,我希望它带我进入不同的视图,但不知道如何操作。我有一个 NavigationLink,我的目的地是不同的视图(Playing.swift,如果需要知道,我使用 Playing() 调用它)

显然我做错了什么,我 [[希望]] 确定这是来自按钮,而不是来自其他视图:

NavigationLink(destination: Playing()) {
    Image("LeftClick")
        .frame(width: UIScreen.screenWidth / 2, height: UIScreen.screenHeight)
}

提前致谢。

【问题讨论】:

    标签: swiftui swiftui-navigationlink


    【解决方案1】:

    在 ZStack 之前添加 NavigationView,如果没有 NavigationView,NavigationLink 将无法工作。

    var body: some View {
      NavigationView {
        ZStack {
        ...
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 2020-05-15
      相关资源
      最近更新 更多