我如何约束子视图,以便不能将其拖到其父视图的范围之外. (iOS) [英] How can I constrain a subview so that it cannot be dragged outside of it's parent view's bounds. (iOS)

查看:347
本文介绍了我如何约束子视图,以便不能将其拖到其父视图的范围之外. (iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制子视图在其父视图中的位置.我在UIView中有一个子视图.可以通过手势识别器拖动子视图.我如何约束子视图,以便不能将其拖到其父视图的范围之外.

How to constrain the position of a subview within its parent view. I have a subview within a UIView. The subview can be dragged via gesture recognizer. How can I constrain the subview so that it cannot be dragged outside of it's parent view's bounds.

推荐答案

要约束可拖动视图,您需要在移动视图时检查其位置,然后在超出边界时将其强制到约束位置.因此,假设您使用touchesMoved:

to constrain a draggable view, you need to check for its position while you move it and then force it to the constrained position if it exceeds the boundaries. So assuming you use touchesMoved :

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    ...

    CGRect frame = mySubview.frame; 
    if (frame.origin.x < boundaryX) { //frame exceeds the horizontal boundary
        frame.origin.x = boundaryX;
        mySubview.frame = frame;
    }
}

因此,假设boundaryX是父视图的原点,则子视图将永远不会超出该边界.您需要对原点yx + widthy + height做同样的事情,以便从各个方面进行约束.

so assuming boundaryX is the origin of the parent view then this way the subview will never exceed that boundary. You need to do the same for origin y and x + width and y + height to do constraints from all sides.

希望这会有所帮助.

这篇关于我如何约束子视图,以便不能将其拖到其父视图的范围之外. (iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆