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


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


1554
2017-12-09 17:44


起源



答案:


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

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
}

11
2017-12-09 17:51



刚试过这个,看起来它甚至在视图仍在超视图的范围内时被调用:/ - mlevi
如果它有帮助我正在做的是基于本教程: raywenderlich.com/71828/uikit-dynamics-tutorial-tossing-views - mlevi
基本上我想在视图离开屏幕后做一些事情 - mlevi
对不起,我误解了你的问题。您需要将该代码放入手势识别器的操作中。 - Stephen Johnson
这样,即使视图仍然在边界内,我输入的代码也会被调用 - mlevi


答案:


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

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
}

11
2017-12-09 17:51



刚试过这个,看起来它甚至在视图仍在超视图的范围内时被调用:/ - mlevi
如果它有帮助我正在做的是基于本教程: raywenderlich.com/71828/uikit-dynamics-tutorial-tossing-views - mlevi
基本上我想在视图离开屏幕后做一些事情 - mlevi
对不起,我误解了你的问题。您需要将该代码放入手势识别器的操作中。 - Stephen Johnson
这样,即使视图仍然在边界内,我输入的代码也会被调用 - mlevi


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

交点大小可以大于零,并且视图仍然位于超视图边界内。

事实证明,我不能使用 equal(to: CGRect) 安全,因为CGFloat准确性。

这是更正版本:

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
2018-01-11 14:48





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

1
2018-02-27 13:24