Last active
December 20, 2022 06:00
-
-
Save ethanhuang13/5cd7718222c5f8d115f8216f1e4a6ea4 to your computer and use it in GitHub Desktop.
[WIP] UIView to check is visible on screen. Not perfect solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIView { | |
func isPossiblyVisible() -> Bool { | |
guard isHidden == false, | |
alpha > 0, | |
bounds != .zero, | |
let window = window, // In a window's view hierarchy | |
window.isKeyWindow, // Does not consider cases covered by another transparent window | |
window.hitTest(convert(center, to: nil), with: nil) != self | |
else { return false } | |
// Checck subviews | |
let invisibleSubviews: Bool = { | |
for subview in subviews { | |
if subview.isPossiblyVisible() { | |
return false | |
} | |
} | |
return true // Including no subviews | |
}() | |
// No subview and no color, its not visible | |
if invisibleSubviews { | |
if (backgroundColor == nil || backgroundColor == .clear) | |
&& (layer.backgroundColor == nil || layer.backgroundColor?.alpha == 0){ | |
return false | |
} | |
} | |
// What about special CALayer cases? | |
return true // maybe, not 100% sure XD | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment