SwiftUI - PresentationButton with modal that is full screen

后端 未结 6 2086
滥情空心
滥情空心 2020-12-08 10:18

I am trying to implement a button that presents another scene with a \"Slide from Botton\" animation.

PresentationButton looked like a good candidate, so I gave it

6条回答
  •  爱一瞬间的悲伤
    2020-12-08 11:01

    This version fixes the compile error present in XCode 11.1 as well as ensures that controller is presented in the style that is passed in.

    import SwiftUI
    
    struct ViewControllerHolder {
        weak var value: UIViewController?
    }
    
    struct ViewControllerKey: EnvironmentKey {
        static var defaultValue: ViewControllerHolder {
            return ViewControllerHolder(value: UIApplication.shared.windows.first?.rootViewController)
    
        }
    }
    
    extension EnvironmentValues {
        var viewController: UIViewController? {
            get { return self[ViewControllerKey.self].value }
            set { self[ViewControllerKey.self].value = newValue }
        }
    }
    
    extension UIViewController {
        func present(style: UIModalPresentationStyle = .automatic, @ViewBuilder builder: () -> Content) {
            let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
            toPresent.modalPresentationStyle = style
            toPresent.rootView = AnyView(
                builder()
                    .environment(\.viewController, toPresent)
            )
            self.present(toPresent, animated: true, completion: nil)
        }
    }
    

    To use this version, the code is unchanged from the previous version.

    struct MyView: View {
    
        @Environment(\.viewController) private var viewControllerHolder: UIViewController?
        private var viewController: UIViewController? {
            self.viewControllerHolder.value
        }
    
        var body: some View {
            Button(action: {
               self.viewController?.present(style: .fullScreen) {
                  MyView()
               }
            }) {
               Text("Present me!")
            }
        }
    }
    

提交回复
热议问题