NSObject+Extension.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // NSObject+Extension.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by Destiny on 2024/4/12.
  6. //
  7. import UIKit
  8. // MARK: - NSObject 属性的扩展
  9. public extension NSObject {
  10. // MARK: 类名(对象方法)
  11. /// 类名
  12. var className: String {
  13. return type(of: self).className
  14. }
  15. // MARK: 类名(类方法)
  16. /// 类名
  17. static var className: String {
  18. return String(describing: self)
  19. }
  20. func rootViewController() -> UIViewController? {
  21. guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first, let rootVC = window.rootViewController else {
  22. return nil
  23. }
  24. return NSObject.top(rootVC: rootVC)
  25. }
  26. private static func top(rootVC: UIViewController?) -> UIViewController? {
  27. if let presentedVC = rootVC?.presentedViewController {
  28. return top(rootVC: presentedVC)
  29. }
  30. if let nav = rootVC as? UINavigationController,
  31. let lastVC = nav.viewControllers.last {
  32. return top(rootVC: lastVC)
  33. }
  34. if let tab = rootVC as? UITabBarController,
  35. let selectedVC = tab.selectedViewController {
  36. return top(rootVC: selectedVC)
  37. }
  38. return rootVC
  39. }
  40. }