我有一个pan手势的视图和一个UIPushBehavior连接到它想知道它是否可以检查视图何时超出了超视图边界。基本上用户抛出视图,我想在视图不在屏幕时运行一些动画。无法弄清楚如何做到这一点。谢谢。
我有一个pan手势的视图和一个UIPushBehavior连接到它想知道它是否可以检查视图何时超出了超视图边界。基本上用户抛出视图,我想在视图不在屏幕时运行一些动画。无法弄清楚如何做到这一点。谢谢。
如果你想检查它是否完全超出它的超视范围,你可以这样做
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
}
如果你想检查它是否完全超出它的超视范围,你可以这样做
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
}
不幸的是,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
}
在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
}