iOS 拖拽动画范围限制

2017/11/02 iOS 动画

方法 1:手势

- (void)panGestureAction:(UIPanGestureRecognizer*)recognizer {
    // Figure out where the user is trying to drag the view.
    UIView *contentView = self.superview;
    CGPoint translation = [recognizer translationInView:contentView];
    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(contentView.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(contentView.frame.size.width - recognizer.view.frame.size.width/2, newCenter.x);
    recognizer.view.center = newCenter;
    [recognizer setTranslation:CGPointZero inView:contentView];
}

方法 2:touchEvent

BOOL isMove;
CGPoint legend_point;
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    isMove = NO;
    UIView *touchView = view/拖拽视图
    UIView *contentView = self.view;//容器
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:contentView];
    if (CGRectContainsPoint(touchView.frame, point)) {
        legend_point = [touch locationInView:touchView];
        isMove = YES;
    }
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesMoved:touches withEvent:event];
    if (!isMove) {
        return;
    }
    @autoreleasepool {
        UIView *touchView = view;//拖拽视图
        UIView *contentView = self.view;//容器
        UITouch *touch = [touches anyObject];
        CGPoint point = [touch locationInView:contentView];
        //转化成相对的中心
        point.x += touchView.frame.size.width/2.0f - legend_point.x;
        point.y += touchView.frame.size.height/2.0f - legend_point.y;
        //限制范围
        if (point.x < touchView.frame.size.width / 2.0f) {
            point.x = touchView.frame.size.width / 2.0f;
        }
        if (point.y < touchView.frame.size.height / 2.0f) {
            point.y = touchView.frame.size.height / 2.0f;
        }

        if (point.x > contentView.frame.size.width - touchView.frame.size.width / 2.0f) {
            point.x = contentView.frame.size.width - touchView.frame.size.width / 2.0f;
        }
        if (point.y > contentView.frame.size.height - touchView.frame.size.height / 2.0f) {
            point.y = contentView.frame.size.height - touchView.frame.size.height / 2.0f;
        }
        touchView.center = point;
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    isMove = NO;
}

Search

    Table of Contents