Giải pháp này cung cấp cho bạn hầu hết các bộ điều khiển nhìn từ trên xuống để bạn có thể xử lý bất kỳ điều kiện đặc biệt trước khi trình bày từ nó. Ví dụ, có thể bạn muốn trình bày bộ điều khiển xem của bạn chỉ khi bộ điều khiển xem nhiều nhất không phải là một bộ điều khiển xem cụ thể.
extension UIApplication {
/// The top most view controller
static var topMostViewController: UIViewController? {
return UIApplication.shared.keyWindow?.rootViewController?.visibleViewController
}
}
extension UIViewController {
/// The visible view controller from a given view controller
var visibleViewController: UIViewController? {
if let navigationController = self as? UINavigationController {
return navigationController.topViewController?.visibleViewController
} else if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.visibleViewController
} else if let presentedViewController = presentedViewController {
return presentedViewController.visibleViewController
} else {
return self
}
}
}
Với điều này bạn có thể trình bày điều khiển xem của bạn từ bất cứ nơi nào mà không cần phải biết những gì hầu hết các bộ điều khiển nhìn từ trên xuống là
UIApplication.topMostViewController?.present(viewController, animated: true, completion: nil)
Hoặc trình bày điều khiển xem của bạn chỉ khi hầu hết các bộ điều khiển nhìn từ trên không phải là một cái nhìn cụ thể điều khiển
if let topVC = UIApplication.topMostViewController, !(topVC is FullScreenAlertVC) {
topVC.present(viewController, animated: true, completion: nil)
}
một điều cần lưu ý là nếu có một UIAlertController hiện đang được hiển thị, UIApplication.topMostViewController
sẽ trả về một UIAlertController
. Trình bày trên đầu trang của một UIAlertController
có hành vi kỳ lạ và nên tránh. Như vậy, bạn nên kiểm tra bằng tay mà !(UIApplication.topMostViewController is UIAlertController)
trước khi trình bày, hoặc thêm một trường hợp else if
trở về con số không nếu self is UIAlertController
extension UIViewController {
/// The visible view controller from a given view controller
var visibleViewController: UIViewController? {
if let navigationController = self as? UINavigationController {
return navigationController.topViewController?.visibleViewController
} else if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.visibleViewController
} else if let presentedViewController = presentedViewController {
return presentedViewController.visibleViewController
} else if self is UIAlertController {
return nil
} else {
return self
}
}
}
làm bạn sử dụng cốt truyện? –
@SpaceDust nope – nebs