DEV Community

Cover image for Is UIView (mostly) visible
Kunal Kamble
Kunal Kamble

Posted on

1 2 1 1 1

Is UIView (mostly) visible

If you've ever needed to check whether a view is visible to the user, you might have used the isHidden property. However, this method falls short in scenarios where a view can appear hidden due to overlapping by other views. To address this, I created a simple extension to provide a more comprehensive visibility check.



extension UIView {

    /// Checkes if the view is (mostly) visible to user or not.
    /// Internaly it checks following things
    ///  - Should NOT be hidden
    ///  - Should NOT be completely transparent
    ///  - Bound should NOT be empty
    ///  - Should be in some window i.e. in view heirarchy
    ///  - Center should be directly visible to user i.e. NOT overlapped with other views
    var isMostlyVisible: Bool {
        guard !isHidden,
              alpha > 0,
              !bounds.isEmpty,
              let window,
              window.hitTest(window.convert(center, from: self.superview), with: nil) == self else {
            return false
        }

        return true
    }

}


Enter fullscreen mode Exit fullscreen mode

Here is the extension in action:

Image description

Thank you for reading.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay