限制view的拖拽范围

先简单说一下需求,有一个view 需要给它添加一个拖拽手势,而且拖拽的时候不能超过屏幕边缘。看到这样一个需求,当然实现的方式有挺多的,你可以通过限制中心点的x值和y值 也可以限制view的最大x和最大y以及最小x最小y,这些都可以,今天要说的是通过限制中心点来做,有需要的可以自己拿去用:

    //添加手势
    UIView * cyanView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    cyanView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:cyanView];
    UIPanGestureRecognizer * panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                                            action:@selector(panGes:)];
    [cyanView addGestureRecognizer:panGestureRecognizer];
-(void)panGes:(UIPanGestureRecognizer *)recognizer{

    CGPoint translation = [recognizer translationInView:self.view];
    CGPoint newCenter = CGPointMake(recognizer.view.center.x+ translation.x,
                                    recognizer.view.center.y + translation.y);
//    限制屏幕范围:
    newCenter.y = MAX(recognizer.view.frame.size.height/2, newCenter.y);
    newCenter.y = MIN(self.view.frame.size.height - recognizer.view.frame.size.height/2, newCenter.y);
    newCenter.x = MAX(recognizer.view.frame.size.width/2, newCenter.x);
    newCenter.x = MIN(self.view.frame.size.width - recognizer.view.frame.size.width/2,newCenter.x);
    recognizer.view.center = newCenter;
    [recognizer setTranslation:CGPointZero inView:self.view];
}

搞定,收工,希望能帮到有需要的小伙伴

你可能感兴趣的:(限制view的拖拽范围)