How to check if a UIView is out of view

I have a view with panorama gestures, and UIPushBehavior connected to it to find out if it can be checked when the view is turned off. Basically the user throws the view, and I want to start some animation when the view leaves the screen. Could not figure out how to do this. Thanks.

+14
ios objective-c iphone swift uiview
source share
3 answers

If you want to check if this is completely due to supervisor restrictions, you can do this

if (!CGRectContainsRect(view.superview.bounds, view.frame)) { //view is completely out of bounds of its super view. } 

If you want to check if only part of it can go beyond, you can do

 if (!CGRectEqualToRect(CGRectIntersection(view.superview.bounds, view.frame), view.frame)) { //view is partially out of bounds } 
+16
source share

Unfortunately, Philip’s answer to partial border checking is not entirely correct on this line: v1.bounds.intersection(v2.frame).width > 0) && (v1.bounds.intersection(v2.frame).height > 0

The intersection size can be greater than zero, and yet the view will be inside the boundaries of the supervisor.

It also turned out that I cannot safely use equal(to: CGRect) due to the accuracy of CGFloat.

Here is the corrected version:

 func outOfSuperviewBounds() -> Bool { guard let superview = self.superview else { return true } let intersectedFrame = superview.bounds.intersection(self.frame) let isInBounds = fabs(intersectedFrame.origin.x - self.frame.origin.x) < 1 && fabs(intersectedFrame.origin.y - self.frame.origin.y) < 1 && fabs(intersectedFrame.size.width - self.frame.size.width) < 1 && fabs(intersectedFrame.size.height - self.frame.size.height) < 1 return !isInBounds } 
+4
source share

EDIT
As already noted, this answer is not entirely correct, please refer to a more voted one.

In Swift 3:

  let v1 = UIView() v1.frame = CGRect(x: 0, y: 0, width: 200, height: 200) v1.backgroundColor = UIColor.red view.addSubview(v1) let v2 = UIView() v2.frame = CGRect(x: 100, y: 100, width: 200, height: 200) v2.backgroundColor = UIColor.blue view.addSubview(v2) if (v1.bounds.contains(v2.frame)) { //view is completely inside super view. } //this should be an or test if (v1.bounds.intersection(v2.frame).width > 0) || (v1.bounds.intersection(v2.frame).height > 0) { //view is partially out of bounds } 
+2
source share

All Articles