Reputation: 19732
Using UIScreen
on iOS is not very common (useful to check scale and traits). UIScreen.main
makes it easy to access these properties when needed.
Having multiple screens on iOS is definitely less common, but possible with AirPlay and, on iPads with USB-C, external monitors. The list of screen instances is available under UIScreen.screens
.
Is there an easy way to know, from a given UIView
, on which screen is it being displayed?
Something like this would be useful:
extension UIView {
var screen: UIScreen {
// Return screen where the view is being displayed (might be `.main`)
}
}
extension UIScreen {
func contains(view: UIView) -> Bool {
// Return true if `view` is being displayed in this screen instance.
}
}
By being displayed, I mean the view is in the view hierarchy. Alternatively, the same question could be asked for a given view controller, that would also solve the problem.
Upvotes: 1
Views: 732
Reputation: 9829
If the view is a descendent of a UIWindow
, get the view's window
and then get the window's screen
, like this:
extension UIView {
var screen: UIScreen? {
window?.screen
}
}
extension UIScreen {
func contains(view: UIView) -> Bool {
view.screen === self
}
}
Upvotes: 2