iPhone/iOS: How to implement Drag and Drop for subviews of a Scrollview?

后端 未结 5 1197
盖世英雄少女心
盖世英雄少女心 2020-12-09 20:50

I am having an horizontal scrollview in an UIViewController, where i have many images in small sizes. I am keeping the images in scrollview because the images a

5条回答
  •  独厮守ぢ
    2020-12-09 21:19

    Getsy,

    Try the code for drag and drop the objects :

    -(void)dragAndDropWithGesture {
    
    UILongPressGestureRecognizer *downwardGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(dragGestureChanged:)];
    [scrollViewAlfabeto addGestureRecognizer:downwardGesture];
        for (UIGestureRecognizer *gestureRecognizer in myscrollView.gestureRecognizers)
        {
           [gestureRecognizer requireGestureRecognizerToFail:downwardGesture];
        }
    }
    
    - (void) dragGestureChanged:(UIPanGestureRecognizer*)gesture
    {
    CGPoint point = [gesture locationInView:scrollViewAlfabeto];
    
    if (gesture.state == UIGestureRecognizerStateBegan) 
    {
    
        [imageViewToMove removeFromSuperview];
        [self.view addSubview:imageViewToMove];
    
        UIView *draggedView = [myscrollView hitTest:point withEvent:nil];
        if ([draggedView isKindOfClass:[UIImageView class]])
        {
            imageViewToMove = (UIImageView*)draggedView;
        }
    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
        imageToMove.center = point;
    }
    else if (gesture.state == UIGestureRecognizerStateEnded     ||
             gesture.state == UIGestureRecognizerStateCancelled ||
             gesture.state == UIGestureRecognizerStateFailed)
    {
        // Determine if dragged view is in an OK drop zone
        // If so, then do the drop action, if not, return it to original location
    
        NSLog(@"point.x final:%f", point.x);
        NSLog(@"point.y final:%f", point.y);
    
        if (CGRectContainsPoint(goal.frame, point)){
            imageToMove.frame = CGRectMake(167, 159, 100, 100);
        }
    
        else{
    
            [imageToMove removeFromSuperview];
            [myscrollView addSubview:imageToMove];
            [imageToMove setFrame:CGRectMake(12, 38, 100, 100)];
            imageToMove = nil;
    
    
    
        }
    }
    
    }
    

    May this code will help you out.

提交回复
热议问题