touchesmoved屏幕边界,我如何限制矩形移出屏幕边界

时间:2017-11-01 09:45:31

标签: ios objective-c

我试图通过屏幕边界来限制矩形的移动。逻辑很简单,你点击里面矩形(不会在哪里)并拖动它。它跟随你的手指,当矩形的边框到达屏幕的边界时它必须停止。

- (void)viewDidLoad {
[super viewDidLoad];
rect.backgroundColor = [UIColor redColor];

}

然后我试着弄清楚水龙头在哪里,如果它在矩形内部我改变了矩形的颜色

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//NSLog(@"%s", __PRETTY_FUNCTION__);
UITouch *touch = touches.anyObject;
if (touch.view == rect) {
    rect.backgroundColor = [UIColor greenColor];
    isSelectedRect = YES;

    CGPoint point = [touch locationInView:self.view];
    CGPoint center = rect.center;

    delta = CGPointMake(point.x - center.x,
                        point.y - center.y);

} else {
    rect.backgroundColor = [UIColor redColor];
    isSelectedRect = NO;
}

}

之后我移动这个矩形

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
    if (isSelectedRect) {
        UITouch *touch = touches.anyObject;
        CGPoint point = [touch locationInView:self.view];
        rect.center = CGPointMake(point.x - delta.x,
                                  point.y - delta.y);
    }
}

最后,我需要编写一行代码来限制屏幕边界的移动。我和三元运算符一起完美。我将不胜感激任何帮助。

3 个答案:

答案 0 :(得分:0)

if (CGRectContainsPoint(boundsRect, point)) {
    rect.center = CGPointMake(point.x - delta.x,
                                  point.y - delta.y);
} 

这里,boundsRect将是设备的矩形。

答案 1 :(得分:0)

使用以下代码替换您的touchesMoved方法。希望它可以帮到你;)

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
  //NSLog(@"%s", __PRETTY_FUNCTION__);
  if (isSelectedRect) {
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.view];
    CGPoint newCenter = CGPointMake(point.x - delta.x,
                          point.y - delta.y);
    CGFloat rectHeight =  rect.frame.size.height;
    CGFloat rectWidth =  rect.frame.size.width;

    CGFloat screenWidth = self.view.frame.size.width;
    CGFloat screenHeight = self.view.frame.size.height;


    if (newCenter.x + rectWidth / 2 > screenWidth) {
      newCenter.x = screenWidth - rectWidth / 2;
    }

    if (newCenter.x - rectWidth / 2 < 0) {
      newCenter.x = rectWidth / 2;
    }

    if (newCenter.y + rectHeight / 2 > screenHeight) {
      newCenter.y = screenHeight - rectHeight / 2;
    }

    if (newCenter.y - rectHeight / 2 >= 0) {
      newCenter.y = rectHeight / 2;
    }

    rect.center = newCenter;
  }
}

答案 2 :(得分:0)

您必须注意,您在touchesMoved函数中移动的点是视图的中心点。为了限制它们超出viewBounds,您必须检查可拖动视图的边界是否超出了您的转换点。

获取实际界限

CGPoint center = rect.center;
CGSize size = rect.size
CGRect originalRect = CGRectMake(center.x - size.width/2, center.y - size.height/2, size.width, size.height);

现在检查给定的rect是否在所需的矩形内。

if (CGRectContainsRect(boundsRect, originalRect)) {
    // Here change the center of the view 
} 

我希望这有帮助。