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)
}
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
SwiftyJD
  • 5,257
  • 7
  • 41
  • 92

3 Answers3

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 :)

Dominik Bucher
  • 2,120
  • 2
  • 16
  • 25
  • 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? – SwiftyJD Sep 26 '17 at 22:50
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
}
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
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.

ManWithBear
  • 2,787
  • 15
  • 27