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

问题描述

我正在学习 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)
}

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

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

NavigationLink 和 .sheet 修饰符似乎与视图实现结合在一起。 有没有人已经在 SwiftUI 中遇到并解决了这种情况?谢谢

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

解决方法

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

enum PresentationType {
    case push,sheet // ...
}

并创建用于激活不同视图的自定义绑定:

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

完整代码:

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")
        }
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...