我有一个带有pan手势的视图,还有一个连接到它的UIPushBehavior,想知道是否有可能检查视图何时超出了超级视图的界限。基本上,用户抛出视图,当视图超出屏幕时,我想运行一些动画。不知道该怎么做。谢谢。
发布于 2014-12-09 17:51:43
如果您想检查它是否完全超出了它的superview界限,您可以这样做
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
}发布于 2018-01-11 14:48:56
不幸的是,Philipp关于部分超出范围检查的答案在这一行中并不完全正确:v1.bounds.intersection(v2.frame).width > 0) && (v1.bounds.intersection(v2.frame).height > 0
交集大小可以大于零,而且视图仍然位于superview边界内。
而且,由于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
}发布于 2017-02-27 13:24:59
编辑
正如所指出的,这个答案并不完全正确,请参考更多被否决的答案。
在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
}https://stackoverflow.com/questions/27385364
复制相似问题