Skip to content

Instantly share code, notes, and snippets.

@ethanhuang13
Last active December 20, 2022 06:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ethanhuang13/5cd7718222c5f8d115f8216f1e4a6ea4 to your computer and use it in GitHub Desktop.
Save ethanhuang13/5cd7718222c5f8d115f8216f1e4a6ea4 to your computer and use it in GitHub Desktop.
[WIP] UIView to check is visible on screen. Not perfect solution
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