如何在 SwiftUI 中动态推送视图或模态呈现视图?

Jos*_*gan 3 presentmodalviewcontroller swiftui swiftui-navigationlink swiftui-navigationview

我正在学习 SwiftUI,目前的重点是实现一个我能够使用 UIKit 实现的方法。我需要创建一个方法来确定是否应该推送视图或基于布尔值以模式方式呈现视图。

在 UIKit 中,我的代码是:

var presentVC = true // boolean that determines whether VC will be presented or pushed

let vc = ViewController() //Your VC that will be pushed or presented

if (presentVC == true) {
     self.presentViewController(vc, animated: true, completion: nil)
} else {
    self.navigationController.pushViewController(vc, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

但在 SwiftUI 中,我不确定如何使用以下方法正确实现:

  • NavigationLink - 用于推送视图
  • .sheet(isPresented:, content:) - 用于以模态方式呈现视图

看来 NavigationLink 和 .sheet 修饰符与视图实现相结合。有人在 SwiftUI 中遇到过并解决过这种情况吗?谢谢

我正在使用 SwiftUI 1.0,因为我需要支持 iOS 13。

paw*_*222 5

一种可能的解决方案是创建具有可用演示类型的自定义枚举:

enum PresentationType {
    case push, sheet // ...
}
Run Code Online (Sandbox Code Playgroud)

并创建一个自定义绑定来激活不同的视图:

func showChildView(presentationType: PresentationType) -> Binding<Bool> {
    .init(
        get: { self.showChildView && self.presentationType == presentationType },
        set: { self.showChildView = $0 }
    )
}
Run Code Online (Sandbox Code Playgroud)

完整代码:

struct ContentView: View {
    @State var presentationType = PresentationType.push
    @State var showChildView = false

    func showChildView(as presentationType: PresentationType) -> Binding<Bool> {
        .init(
            get: { self.showChildView && self.presentationType == presentationType },
            set: { self.showChildView = $0 }
        )
    }

    var body: some View {
        NavigationView {
            VStack {
                Button(action: {
                    self.presentationType = .push
                    self.showChildView = true
                }) {
                    Text("Present new view as Push")
                }
                Button(action: {
                    self.presentationType = .sheet
                    self.showChildView = true
                }) {
                    Text("Present new view as Sheet")
                }
            }
            .navigationBarTitle("Main view", displayMode: .inline)
            .background(
                NavigationLink(
                    destination: ChildView(),
                    isActive: self.showChildView(presentationType: .push),
                    label: {}
                )
            )
        }
        .sheet(isPresented: self.showChildView(presentationType: .sheet)) {
            ChildView()
        }
    }
}

struct ChildView: View {
    var body: some View {
        ZStack {
            Color.red
            Text("Child view")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这正是我想要在 SwiftUI 中实现的。非常感谢 pawell2222! (2认同)