在 iOS 开发中,弹框、浮出层和模态视图是常见的用户界面元素。它们用于在应用程序的主界面上显示临时内容或其他功能。
在 iOS 13 之前,我们使用
present(viewController:animated:completion:)
方法来弹出模态视图。在 iOS 13 中,Apple 引入了新的
PresentModalViewController
协议,为弹出模态视图提供了更现代、更灵活的方式。
PresentModalViewController
协议定义了三个方法,允许我们控制模态视图的呈现和关闭:
func presentModalViewController(_ viewController: UIViewController)
func dismissModalViewController(animated: Bool, completion: (() -> Void)?)
func shouldPresentModalViewController(_ viewController: UIViewController) -> Bool
presentModalViewController()
方法用于显示模态视图。
dismissModalViewController()
方法用于关闭模态视图。
shouldPresentModalViewController()
方法是一个可选方法,它允许我们控制是否允许模态视图显示。
.fullScreenCover(isPresented:, content:)
修饰符来显示模态视图。
isPresented
参数接受一个
Binding
值,该值确定模态视图是否应该显示。
content
参数接收一个闭包,该闭包返回模态视图的内容:```swiftstruct ContentView: View {@State private var isModalPresented = falsevar body: some View {Button(action: {isModalPresented = true}) {Text("Show Modal")}.fullScreenCover(isPresented: $isModalPresented, content: {ModalView()})}}```
present()
方法来显示模态视图。
present()
方法接受两个参数:要显示的视图控制器和一个
UIModalPresentationStyle
值,该值指定模态视图的呈现方式:```swiftfunc presentModalViewController() {let modalViewController = ModalViewController()modalViewController.modalPresentationStyle = .fullScreenpresent(modalViewController, animated: true, completion: nil)}```
dismiss()
方法。
dismiss()
方法接受两个参数:是否以动画方式关闭模态视图和一个完成闭包,该闭包在模态视图关闭后执行:```swiftfunc dismissModalViewController() {dismiss(animated: true, completion: nil)}```
shouldPresentModalViewController()
方法来控制是否显示模态视图。
shouldPresentModalViewController()
方法接受一个视图控制器参数并返回一个布尔值,指示模态视图是否应该显示:```swiftfunc shouldPresentModalViewController(_ viewController: UIViewController) -> Bool {// 检查是否满足显示模态视图的条件// 如果满足,返回 true;否则,返回 false}```
PresentModalViewController
协议为我们在 iOS 和 SwiftUI 中以灵活且现代的方式显示模态视图提供了强大的功能。通过了解此协议的方法,我们可以创建具有良好用户体验和高响应性的应用程序。
AI工具
本文地址:https://www.badfl.com/article/f46eaed65aa59e625b8f.html