[英]How to check if a UIView is out of its superview bounds
我有一個帶有平移手勢的視圖和一個連接到它的 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
}
不幸的是,菲利普對部分越界檢查的回答在這一行中並不完全正確: 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
}
編輯
正如所指出的,這個答案並不完全正確,請參閱更多贊成的答案。
在 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
}
斯威夫特 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
}
接受答案的 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
}
如果要檢查子視圖的一部分是否超出其超級視圖的范圍,請嘗試以下操作:
在 x 軸的情況下
if subview.frame.maxX >= superview.bounds.maxX {
your code
}
if subview.frame.minX <= superview.bounds.minX {
your code
}
您可以對 y 軸嘗試相同的操作,將 minX 和 maxX 替換為 minY 和 maxY
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.