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

3

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

在UIKit中,我的代码如下:


```swift if shouldPush { navigationController?.pushViewController(viewController, animated: true) } else { present(viewController, animated: true) } ```
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。

1个回答

5
一个可能的解决方案是创建一个自定义枚举,其中包含可用的演示类型:
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")
        }
    }
}

2
这正是我正在尝试在SwiftUI中实现的。非常感谢pawello2222! - Josh Byanec McFergan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接