Search code examples
objective-ciosxcodedrag-and-dropuiimageview

How do I drag & drop and center an image between UIImageViews?


I am developing a chess app and currently I have a simple setup: background of the board and UIImageView for all the cells. So far I have managed to successfully drag & drop images around the board with the use of UITouch and CGPoint.

My problem is that I can drag & drop these images anywhere in my app and I need to create code to set boundaries on both the board and the images. Right now my images can be dragged and dropped on top of each other, or in between cells when they need to be dropped within them, or they can be dropped outside the bounds of the board where they need to be within its bounds. Therefore this is an issue of setting boundaries.

Code for handling drag & drop events:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];

    CGPoint touchLocation = [touch locationInView:[self view]];   

    for (UIImageView *piece in chessCells) {
        if([touch view] == piece){
            piece.center = touchLocation;
        }
    }

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [self touchesBegan:touches withEvent:event];
}

About the for loop:

All the cells in my board are blank IBOutlets with UIImageViews, which I organize by keeping them in a NSArray called 'chessCells'. I have a method that displays the images in their respective cells when the app starts. From this point I am be able to grab them and move them around freely across the chessboard... but as I have found, a bit too freely.


Solution

  • You should try with CGRectIntersectRect add this to your code

    if (CGRectIntersectsRect(yourImgFrame1, yourImgFrame2)) {
        //do What ever you want
    }
    

    with this code when your yourImgFrame1 intersects yourImgFrame2 you can perform any action

    Good Luck