Equivalent of UIApplication.shared.preferredContentSizeCategory in app extension
Asked Answered
M

1

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.

Minutes answered 30/12, 2016 at 0:9 Comment(4)
Is the view controller not providing the correct value? What about self.view.window.preferredContentSizeCategory?Unbidden
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. I could just compile that part out, but I'd rather actually support dynamic type in extensions.Minutes
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. ;-)Unbidden
What does UIScreen.main.preferredContentSizeCategory return? I think UIScreen.main is available in extensions.Unbidden
F
9

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

Fuel answered 24/11, 2017 at 15:16 Comment(1)
NB you can't use this property in viewDidLoad but it is available in viewWillAppearMercurochrome

© 2022 - 2024 — McMap. All rights reserved.