How to check to see if one view is on top of another view?
Asked Answered
H

3

5

Currently there is a scrollview (whole screen) that sits behind a uiview (bottom portion of the screen). I"m trying to check whether or not a label on the scroll is covered by the uiview (this happens with iphone se). Is there a way to check if the uiview is covering the label on the scrollview? I tried using the center cgpoint of a label on the scrollview to see if its smaller than a point on the uiview but it won't allow me to compare two cgpoints for size:

if atmLabel.center < CGPoint(x: 156, y: 570) {
    buttonView.dropShadow(shadowOpacity: 0.5)
}
Honeymoon answered 26/9, 2017 at 22:42 Comment(0)
T
10

For point checking, you should use

contains function of CGRect... in short this should work

 let view = UIView()
 let label = UILabel()

 if label.frame.contains(view.frame) {
    //Do your stuff...
 }

You can use the view hiearchy with Xcode with this button enter image description here

Or you can simply print out on the current viewController subviews

print(self.view.subviews)

this prints out array of UIView subclasses sorted by ascending order of layer on the view... I recommend the first way of debugging :)

Tetraspore answered 26/9, 2017 at 22:49 Comment(1)
That's great for debugging, but I need it to execute something if the label is covered. Is there a way to find out in code?Honeymoon
P
9

If you want to see if two views overlap in code, I think this should work:

if view1.frame.intersects(view2.frame) {
    // handle overlap
}
Palisade answered 26/9, 2017 at 22:56 Comment(0)
S
5

Your view hierarchy:

parentView
- scrollView
- - label
- topView

The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.

https://developer.apple.com/documentation/uikit/uiview/1622621-frame

You can't simply compare frames of label and topView, because frame is position in superview's coordinates aka topView.frame is in parentView coordinates and label.frame is in scrollView coordinates.

So you need to transform either label to parentView or topView to scrollView coordinates. Let's go with first variant:

let frameInParent = parentView.convert(label.frame, from: label.superview)

After that you can check if this frame intersects with topView's:

let isOverlaps = frameInParent.intersects(topView.frame)

But this only true if you don't use any transforms on views, because again frame documentation:

Warning

If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.

Squire answered 9/10, 2018 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.