限制superview中的视图

Lal*_*h B 7 iphone objective-c ipad ios

我正在尝试使用触摸移动方法在另一个UIView - "B"(SuperView)中移动UIView - "A"(子视图).我能够将UIView移到superview之外.我想限制Superview界限内的UIView.有没有办法可以有一个通用的方法来测试子视图是否在superview的可见矩形内?

Pra*_*d G 7

使用clipsToBounds方法或 CGRectContainsRect

youSuperView.clipsToBounds = YES;
Run Code Online (Sandbox Code Playgroud)

我认为这对你有所帮助


dan*_*anh 6

听起来你想要限制子视图(viewA)的运动总是被superview(viewB)完全包含.CGRectContainsRect是正确的答案,但必须谨慎应用,因为在其superview的坐标系中指定了子视图框架.

// inside touches moved, compute the newViewAFrame based on the movement
// but only assign it if it meets the containment constraint:

if (CGRectContainsRect(viewB.bounds, newViewAFrame)) {
    viewA.frame = newViewAFrame;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们在检查中没有提到viewB.frame.viewB在其父级中的位置与viewB是否包含viewA无关.