10

My open source library needs to be able to call UIApplication.shared.preferredContentSizeCategory. But UIApplication.shared is unavailable in extensions. The build error suggests that I find a view controller-based way to solve my problem, but I'm writing a library, so I don't have access to any view controllers. Is there a way to get the root view controller of an extension, or a way to get the outermost UITraitEnvironment?

I support iOS 9+, but this feature could be 10+ if that makes it possible.

Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
  • Is the view controller not providing the correct value? What about `self.view.window.preferredContentSizeCategory`? – Léo Natan Dec 30 '16 at 01:09
  • I'm not in a view or a window. This is an instance function that I'm adding to `UITraitCollection`, and I want to find the current trait environment's current trait collection. You can see the reasoning [here](https://github.com/Raizlabs/BonMot/issues/251). I could just compile that part out, but I'd rather actually support dynamic type in extensions. – Zev Eisenberg Dec 30 '16 at 01:11
  • I could just mention that `sharedApplication` actually exists in extensions, just artificially blocked due to how Apple have set up their extensions lifecycle. `UIApplication.value(forKey: "sharedApplication") as! UIApplication` will give you what you want. ;-) – Léo Natan Dec 30 '16 at 01:13
  • What does `UIScreen.main.preferredContentSizeCategory` return? I think `UIScreen.main` is available in extensions. – Léo Natan Dec 30 '16 at 01:36

1 Answers1

9

You can use UIScreen.main.traitCollection.preferredContentSizeCategory. The preferredContentSizeCategory property is available on iOS 10 or later.

Pablo
  • 186
  • 2
  • 4
  • NB you can't use this property in `viewDidLoad` but it is available in `viewWillAppear` – lewis Jan 03 '19 at 16:05