在 UIKit 中,我使用下面的代码来呈现一个具有演示风格crossDissolve 的模态视图控制器
controller.modalTransitionStyle = .crossDissolve
controller.modalPresentationStyle = .overFullScreen
UIApplication.topViewController()?.present(controller, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
但是我如何在 swiftUI 中实现这一点呢?
您可以像这样在 UIViewController 上进行扩展:
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<Content: View>(style: UIModalPresentationStyle = .automatic, transitionStyle: UIModalTransitionStyle = .coverVertical, @ViewBuilder builder: () -> Content) {
let toPresent = UIHostingController(rootView: AnyView(EmptyView()))
toPresent.modalPresentationStyle = style
toPresent.modalTransitionStyle = transitionStyle
toPresent.rootView = AnyView(
builder()
.environment(\.viewController, toPresent)
)
self.present(toPresent, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
并在 SwiftUI 代码中根据需要使用它:
struct ContentView: View {
@Environment(\.viewController) private var viewControllerHolder: UIViewController?
private var viewController: UIViewController? {
self.viewControllerHolder
}
var body: some View {
Button(action: {
self.viewController?.present(style: .fullScreen, transitionStyle: .coverVertical) {
Text("OK")
}
}) {
Text("Present me!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以根据需要更改演示和过渡风格
| 归档时间: |
|
| 查看次数: |
2149 次 |
| 最近记录: |