在 iOS 13 全屏模式下呈现模态

Presenting modal in iOS 13 fullscreen

在 iOS 13 中,模态视图控制器在呈现时有一个新行为。

现在默认情况下它不是全屏的,当我尝试向下滑动时,应用程序会自动关闭视图控制器。

如何防止这种行为并返回到旧的全屏模式 vc?

谢谢

随着 iOS13,如 WWDC 2019 期间 Platforms State of the Union 所述,Apple 引入了新的默认卡片演示。为了强制全屏,你必须明确指定它:

let vc = UIViewController()
vc.modalPresentationStyle = .fullScreen //or .overFullScreen for transparency
self.present(vc, animated: true, completion: nil)

我添加了一条可能对某人有用的信息。如果您有任何故事板转场,要返回旧样式,您需要将 kind 属性 设置为 Present Modally 并且Presentation 属性 到 Full Screen.

我在启动屏幕后的初始视图中遇到了这个问题。由于我没有定义 segue 或逻辑,因此对我的修复是将演示文稿从自动切换到全屏,如下所示:

作为提示:如果您调用 present 给嵌入在 NavigationController 中的 ViewController,您必须将 NavigationController 设置为 .fullScreen 而不是 VC.

您可以像@davidbates 那样做,也可以通过编程方式(像@pascalbros)。

同样适用于UITabViewController

NavigationController 的示例场景:

    //BaseNavigationController: UINavigationController {}
    let baseNavigationController = storyboard!.instantiateViewController(withIdentifier: "BaseNavigationController")
    var navigationController = UINavigationController(rootViewController: baseNavigationController)
    navigationController.modalPresentationStyle = .fullScreen
    navigationController.topViewController as? LoginViewController
    self.present(navigationViewController, animated: true, completion: nil)

如果您的 UITabController 带有带有嵌入式导航控制器的屏幕,则必须将 UITabController Presentation 设置为全屏,如下图所示

Objective-C 用户

只需使用此代码

 [vc setModalPresentationStyle: UIModalPresentationFullScreen];

或者如果你想在 iOS 13.0 中添加它,那么使用

 if (@available(iOS 13.0, *)) {
     [vc setModalPresentationStyle: UIModalPresentationFullScreen];
 } else {
     // Fallback on earlier versions
 }
let Obj = MtViewController()
Obj.modalPresentationStyle = .overFullScreen
self.present(Obj, animated: true, completion: nil)

// 如果你想禁用滑动关闭,添加行

Obj.isModalInPresentation = true

查看 Apple Document 了解更多信息。

我使用调配 ios 13

import Foundation
import UIKit

private func _swizzling(forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
    if let originalMethod = class_getInstanceMethod(forClass, originalSelector),
       let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) {
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }
}

extension UIViewController {

    static let preventPageSheetPresentation: Void = {
        if #available(iOS 13, *) {
            _swizzling(forClass: UIViewController.self,
                       originalSelector: #selector(present(_: animated: completion:)),
                       swizzledSelector: #selector(_swizzledPresent(_: animated: completion:)))
        }
    }()

    @available(iOS 13.0, *)
    @objc private func _swizzledPresent(_ viewControllerToPresent: UIViewController,
                                        animated flag: Bool,
                                        completion: (() -> Void)? = nil) {
        if viewControllerToPresent.modalPresentationStyle == .pageSheet
                   || viewControllerToPresent.modalPresentationStyle == .automatic {
            viewControllerToPresent.modalPresentationStyle = .fullScreen
        }
        _swizzledPresent(viewControllerToPresent, animated: flag, completion: completion)
    }
}

然后放这个

UIViewController.preventPageSheetPresentation

某处

例如在 AppDelegate 中

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool {

    UIViewController.preventPageSheetPresentation
    // ...
    return true
}

以上答案和建议是正确的,下面是另一个版本,以编程方式使用的高效方法。

#1 创建了一个 UIView 扩展

#2 创建方法 ()

//#1
extension UIViewController {

//#2
func presentLocal(_ viewControllerToPresent: UIViewController, animated flag: 
Bool, completion: (() -> Void)? = nil) {

//Reusing below 2 lines :-)
viewControllerToPresent.modalPresentationStyle = .overCurrentContext
self.present(viewControllerToPresent, animated: flag, completion: completion)

  }
}

如下调用

let vc = MyViewController()
let nc = UINavigationController(rootViewController: vc)
sourceView.presentLocal(nc, animated: true, completion: nil)

let vc = MyViewController()
sourceView.presentLocal(vc, animated: true, completion: nil)

有多种方法可以做到这一点,我认为每一种都适合一个项目而不适合另一个项目,所以我想我会把它们留在这里也许其他人会 运行 不同的情况。

1- 覆盖当前

如果您有 BaseViewController,您可以覆盖 present(_ viewControllerToPresent: animated flag: completion:) 方法。

class BaseViewController: UIViewController {

  // ....

  override func present(_ viewControllerToPresent: UIViewController,
                        animated flag: Bool,
                        completion: (() -> Void)? = nil) {
    viewControllerToPresent.modalPresentationStyle = .fullScreen
    super.present(viewControllerToPresent, animated: flag, completion: completion)
  }

  // ....
}

使用这种方式,您无需对任何 present 调用进行任何更改,因为我们只是覆盖了 present 方法。

2- 扩展名:

extension UIViewController {
  func presentInFullScreen(_ viewController: UIViewController,
                           animated: Bool,
                           completion: (() -> Void)? = nil) {
    viewController.modalPresentationStyle = .fullScreen
    present(viewController, animated: animated, completion: completion)
  }
}

用法:

presentInFullScreen(viewController, animated: true)

3- 对于一个 UIViewController

let viewController = UIViewController()
viewController.modalPresentationStyle = .fullScreen
present(viewController, animated: true, completion: nil)

4- 来自故事板

Select 一个 segue 并将演示文稿设置为 FullScreen

5- 混合

extension UIViewController {

  static func swizzlePresent() {

    let orginalSelector = #selector(present(_: animated: completion:))
    let swizzledSelector = #selector(swizzledPresent)

    guard let orginalMethod = class_getInstanceMethod(self, orginalSelector), let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) else{return}

    let didAddMethod = class_addMethod(self,
                                       orginalSelector,
                                       method_getImplementation(swizzledMethod),
                                       method_getTypeEncoding(swizzledMethod))

    if didAddMethod {
      class_replaceMethod(self,
                          swizzledSelector,
                          method_getImplementation(orginalMethod),
                          method_getTypeEncoding(orginalMethod))
    } else {
      method_exchangeImplementations(orginalMethod, swizzledMethod)
    }

  }

  @objc
  private func swizzledPresent(_ viewControllerToPresent: UIViewController,
                               animated flag: Bool,
                               completion: (() -> Void)? = nil) {
    if #available(iOS 13.0, *) {
      if viewControllerToPresent.modalPresentationStyle == .automatic {
        viewControllerToPresent.modalPresentationStyle = .fullScreen
      }
    }
    swizzledPresent(viewControllerToPresent, animated: flag, completion: completion)
   }
}

用法:
在你的 AppDelegate 里面 application(_ application: didFinishLaunchingWithOptions) 添加这一行:

UIViewController.swizzlePresent()

使用这种方式,您无需对任何现有调用进行任何更改,因为我们将在运行时替换现有方法实现。
如果你需要知道什么是 swizzling,你可以检查这个 link: https://nshipster.com/swift-objc-runtime/

另一种方法是在您的应用程序中拥有自己的基础 viewcontroller 组件,并仅使用基本设置实现指定和必需的初始化程序,如下所示:

class MyBaseViewController: UIViewController {

//MARK: Initialisers

/// Alternative initializer which allows you to set the modal presentation syle
/// - Parameter modalStyle: the presentation style to be used
init(with modalStyle:UIModalPresentationStyle) {
    super.init(nibName: nil, bundle: nil)
    self.setup(modalStyle: modalStyle)
}

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    // default modal presentation style as fullscreen
    self.setup(modalStyle: .fullScreen)
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    // default modal presentation style as fullscreen
    self.setup(modalStyle: .fullScreen)
}

//MARK: Private

/// Setup the view
///
/// - Parameter modalStyle: indicates which modal presentation style to be used
/// - Parameter modalPresentation: default true, it prevent modally presented view to be dismissible with the default swipe gesture
private func setup(modalStyle:UIModalPresentationStyle, modalPresentation:Bool = true){
    if #available(iOS 13, *) {
        self.modalPresentationStyle = modalStyle
        self.isModalInPresentation = modalPresentation
    }
}

注意:如果您的视图控制器包含在实际以模态方式呈现的导航控制器中,那么导航控制器应该以相同的方式解决问题(意思是,让您的以相同方式定制的自定义导航控制器组件

在 Xcode 11.1、iOS 13.1 和 iOS 12.4

上测试

希望对您有所帮助

class MyViewController: UIViewController {

    convenience init() {
        self.init(nibName:nil, bundle:nil)
        self.modalPresentationStyle = .fullScreen
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

无需为每个视图控制器调用 self.modalPresentationStyle = .fullScreen,您可以子类化 UIViewController 并在任何地方使用 MyViewController

这是一个简单的解决方案,无需编写一行代码。

  • Select 在 Storyboard 中查看控制器
  • Select属性检查器
  • 按照下图将演示文稿 "Automatic" 设置为 "FullScreen"

此更改使 iPad 应用行为符合预期,否则新屏幕将作为弹出窗口显示在屏幕中央。

所有其他答案都足够了,但对于像我们这样的大型项目以及在代码和情节提要中进行导航的地方,这是一项艰巨的任务。

对于那些积极使用故事板的人。这是我的建议:使用正则表达式。

以下格式不适用于全屏页面:

<segue destination="Bof-iQ-svK" kind="presentation" identifier="importSystem" modalPresentationStyle="fullScreen" id="bfy-FP-mlc"/>

以下格式适用于全屏页面:

<segue destination="7DQ-Kj-yFD" kind="presentation" identifier="defaultLandingToSystemInfo" modalPresentationStyle="fullScreen" id="Mjn-t2-yxe"/>

以下与 VS CODE 兼容的正则表达式会将所有旧样式页面转换为新样式页面。如果您使用其他正则表达式 engines/text 编辑器,您可能需要转义特殊字符。

搜索正则表达式

<segue destination="(.*)"\s* kind="show" identifier="(.*)" id="(.*)"/>

替换正则表达式

<segue destination="" kind="presentation" identifier="" modalPresentationStyle="fullScreen" id=""/>

最初,modalPresentationStyle 的默认值为 fullscreen,但在 iOS 13 中,它的更改为 UIModalPresentationStyle.automatic.

如果你想制作全屏视图控制器,你必须将 modalPresentationStyle 更改为 fullScreen

参考UIModalPresentationStyle apple documentation for more details and refer apple human interface guidelines 哪里应该使用哪种模式。

这是Objective-C

的解决方案
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:@"ViewController"];

vc.modalPresentationStyle = UIModalPresentationFullScreen;

[self presentViewController:vc animated:YES completion:nil];

为 UIViewController 创建一个类别(比如 UIViewController+PresentationStyle)。添加以下代码。

 -(UIModalPresentationStyle)modalPresentationStyle{
     return UIModalPresentationStyleFullScreen;
}

你可以轻松做到 打开你的故事板作为源代码并搜索 kind="presentation",在所有带有 kind = presentation 的 seague 标签中添加一个额外的属性 modalPresentationStyle="fullScreen"


一个班轮:

modalPresentationStyle需要在navigationController上设置.


iOS 13 and below iOS version fullScreen with overCurrentContext and navigationController

测试代码

let controller = UIViewController()
let navigationController = UINavigationController(rootViewController: controller)
navigationController.modalPresentationStyle = .overCurrentContext
self.navigationController?.present(navigationController, animated: true, completion: nil)

modalPresentationStyle 需要设置在 navigationController

我需要两者都做:

  1. 将演示样式设置为全屏

  2. 将顶部栏设置为半透明导航栏

这是我使用类别修复 ObjectiveC 的版本。使用这种方法,您将拥有默认的 UIModalPresentationStyleFullScreen 行为,直到明确设置另一个行为为止。

#import "UIViewController+Presentation.h"
#import "objc/runtime.h"

@implementation UIViewController (Presentation)

- (void)setModalPresentationStyle:(UIModalPresentationStyle)modalPresentationStyle {
    [self setPrivateModalPresentationStyle:modalPresentationStyle];
}

-(UIModalPresentationStyle)modalPresentationStyle {
    UIModalPresentationStyle style = [self privateModalPresentationStyle];
    if (style == NSNotFound) {
        return UIModalPresentationFullScreen;
    }
    return style;
}

- (void)setPrivateModalPresentationStyle:(UIModalPresentationStyle)modalPresentationStyle {
    NSNumber *styleNumber = [NSNumber numberWithInteger:modalPresentationStyle];
     objc_setAssociatedObject(self, @selector(privateModalPresentationStyle), styleNumber, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIModalPresentationStyle)privateModalPresentationStyle {
    NSNumber *styleNumber = objc_getAssociatedObject(self, @selector(privateModalPresentationStyle));
    if (styleNumber == nil) {
        return NSNotFound;
    }
    return styleNumber.integerValue;
}

@end

最新 iOS 13 和 Swift 5.x

let vc = ViewController(nibName: "ViewController", bundle: nil)

vc.modalPresentationStyle = .fullScreen

self.present(vc, animated: true, completion: nil)

我是通过方法swizzling(Swift 4.2)实现的:

创建一个UIViewController扩展如下

extension UIViewController {

    @objc private func swizzled_presentstyle(_ viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) {

        if #available(iOS 13.0, *) {
            if viewControllerToPresent.modalPresentationStyle == .automatic || viewControllerToPresent.modalPresentationStyle == .pageSheet {
                viewControllerToPresent.modalPresentationStyle = .fullScreen
            }
        }

        self.swizzled_presentstyle(viewControllerToPresent, animated: animated, completion: completion)
    }

     static func setPresentationStyle_fullScreen() {

        let instance: UIViewController = UIViewController()
        let aClass: AnyClass! = object_getClass(instance)

        let originalSelector = #selector(UIViewController.present(_:animated:completion:))
        let swizzledSelector = #selector(UIViewController.swizzled_presentstyle(_:animated:completion:))

        let originalMethod = class_getInstanceMethod(aClass, originalSelector)
        let swizzledMethod = class_getInstanceMethod(aClass, swizzledSelector)
        if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
        method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
}

并且在 AppDelegate 中,在 application:didFinishLaunchingWithOptions 中:通过调用以下代码来调用 swizzling 代码:

UIViewController.setPresentationStyle_fullScreen()

快速解决。上面已经有非常好的答案。我还添加了我的快速 2 点输入,显示在屏幕截图中。

  1. 如果您不使用 Navigation Controller,则从 Right Menu Inspector 将 Presentation 设置为 Full Screen

  2. 如果您正在使用 Navigation Controller 那么默认情况下它会全屏显示,您什么都不用做。

这对我有用

let vc = self.storyboard?.instantiateViewController(withIdentifier: "storyboardID_cameraview1") as! CameraViewController
  
vc.modalPresentationStyle = .fullScreen
    
self.present(vc, animated: true, completion: nil)`

navigationController.modalPresentationStyle 设置为 .fullScreen 已在此处重复了一千多次,但让我向您介绍另一个导致 UIViewController / UINavigationController 无效的阻止程序尽管所有属性都已正确设置,但仍显示在 fullscreen 中。

在我的案例中,罪魁祸首隐藏在这一行中

navigationController?.presentationController?.delegate = self

显然,在设置 UIAdaptivePresentationControllerDelegate 时,您需要在可选委托方法中指定呈现样式

    public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        presentationStyle
    }