如何检查UIView是否超出其超视图范围

时间:2014-12-09 17:44:24

标签: ios objective-c iphone swift uiview

我有一个带有平移手势的视图和一个连接到它的UIPushBehavior,想要知道它是否可以检查视图何时超出超视图范围。基本上用户扔视图,我想在视图不在屏幕时运行一些动画。无法弄清楚如何做到这一点。感谢。

5 个答案:

答案 0 :(得分:14)

如果你想检查它是否完全超出它的超视范围,你可以这样做

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

如果你想检查它的一部分是否超出范围,你可以

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

答案 1 :(得分:2)

不幸的是,Philipp在部分界外检查中的答案在这一行中并不完全正确: v1.bounds.intersection(v2.frame).width > 0) && (v1.bounds.intersection(v2.frame).height > 0

交点大小可以大于零,但视图仍然位于超视图范围内。

事实证明,由于CGFloat的准确性,我无法安全使用equal(to: CGRect)

以下是更正版本:

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
}

答案 2 :(得分:1)

在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.
    }

    if (v1.bounds.intersection(v2.frame).width > 0) && (v1.bounds.intersection(v2.frame).height > 0)
    {
        //view is partially out of bounds
    }

答案 3 :(得分:1)

雨燕5

func isView(_ innerView: UIView, outOfViewFrame outerViewFrame: CGRect) -> Bool {
        let intersectedFrame = outerViewFrame.intersection(innerView.frame)
        let isInBounds = abs(intersectedFrame.origin.x - innerView.frame.origin.x) < 1 &&
            abs(intersectedFrame.origin.y - innerView.frame.origin.y) < 1 &&
            abs(intersectedFrame.size.width - innerView.frame.size.width) < 1 &&
            abs(intersectedFrame.size.height - innerView.frame.size.height) < 1
        return !isInBounds
    }

答案 4 :(得分:0)

已接受答案的Swift 5版本:

// Full
if subview.superview!.bounds.contains(subview.frame) { 
  // Do something 
}

// Partial
let intersection = subview.superview!.bounds.intersection(subview.frame)
if !intersection.equalTo(subview.frame) { 
  // Do something
}