拖放UIButton但限制边界 [英] Drag and drop UIButton but limit to boundaries

查看:97
本文介绍了拖放UIButton但限制边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是要求给出反应,而只是向正确的方向微调将不胜感激。我的搜索没有任何好处。

I’m not asking for givemesamplecodenow responses, just a nudge in the right direction would be much appreciated. My searches haven’t been any good.

我有一个UIButton,我可以在屏幕周围自由移动。

I have a UIButton that I am able to move freely around the screen.

我想限制此对象上的拖动区域,因此只能上下移动或并排移动。我相信我需要得到边界的x,y坐标,然后限制这个区域以外的运动。但是这远远不如我所知道的那样。我的知识不会比这更进一步。

I would like to limit the drag area on this object so it can only be moved up and down or side to side. I believe I need to get the x,y coordinates of the boundaries and then restrict movement outside this area. But that’s a far as I have got. My knowledge doesn’t stretch any further than that.

有没有人实现过去类似的东西?

Has anyone implemented something similar in the past?

Adam

推荐答案

所以让我们说你正在拖动操作。通过将其中心设置到任何手势导致运动的中心,您正在移动按钮实例。

So let's say you're in the middle of the drag operation. You're moving the button instance around by setting its center to the center of whatever gesture is causing the movement.

您可以通过测试手势的中心并重置如果你不喜欢它们的中心值。以下假设一个按钮连接到所有触摸拖动事件的动作,但是如果您使用手势识别器或触摸屏,则该原则仍然适用.Began:和朋友。

You can impose restrictions by testing the gesture's center and resetting the center values if you don't like them. The below assumes a button wired to an action for all Touch Drag events but the principle still applies if you're using gesture recognizers or touchesBegan: and friends.

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];

    if (point.y > 200)
    {
        point.y = 200; //No dragging this button lower than 200px from the origin!
    }

    sender.center = point;
}

如果你想要一个仅在一个轴上滑动的按钮,这很简单:

If you want a button that slides only on one axis, that's easy enough:

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];  
    point.y = sender.center.y; //Always stick to the same y value

    sender.center = point;
}

或者你希望按钮只能在特定视图的区域内拖动。这可能更容易定义,如果你的边界是复杂的。

Or perhaps you want the button draggable only inside the region of a specific view. This might be easier to define if your boundaries are complicated.

- (IBAction)handleDrag:(UIButton *)sender forEvent:(UIEvent *)event 
{   
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.someView];

    if ([self.someView pointInside:point withEvent:nil])
    {
        sender.center = point; 
        //Only if the gesture center is inside the specified view will the button be moved
    }
}

这篇关于拖放UIButton但限制边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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