Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Drawing a grid view for dragging/dropping objects that snap to that grid

I am working on a project that requires a custom view segmented into squares. You need to be able to drag another view over it and when you drop that object it will snap to the grid squares. I also need to be able to iterate over every square in the grid and determine if an object is inside that particular grid square.

I realize this is a bit of a general question but I'm just looking for any direction on where to start, classes or frameworks that might already exist for reference. Any direction at all would be greatly appreciated. Thanks.

like image 784
HenryGale Avatar asked Nov 03 '22 17:11

HenryGale


1 Answers

Question #1: User needs to be able to drag another view over it and when you drop that object it will snap to the grid squares.

Lets say you are dragging a UIView. On the touchesEnded of the UIView I would use the center property which contains the x and y coordinate center values of the UIView and pass that to a function that tests to see which grid square it is inside of.

This would look like this (assume UIView is name draggingView):

for (CGRect gridSquare in gridArray) {
    if (CGRectContainsPoint(gridRect, draggingView.center)) {
        // Return the gridSquare that contains the object
    }
}

Now in case you are wondering what gridArray is, it is an array of all the grid squares that make up your game board. If you need help creating this let me know.

Question #2: User needs to be able to iterate over every square in the grid and determine if an object is inside that particular grid square.

If you were able to follow along above then this is quite easy. While iterating over the grid squares you could use the gridSquare origin values to see if any of the draggingView subviews have the same origin. Using this you can return the UIView that is inside a particular square. See below:

- (UIView *)findViewInSquare {
    for (CGRect rect in gridArray) {
        for (UIView *view in [self.view subViews]) {
            if (CGPointEqualToPoint(view.frame.origin, rect.origin)) {
                return view;   // Returns the view in the grid square
            }
        }
    }
    return nil;
}

Hopefully this all makes sense, and let me know if you need any clarification.

like image 166
dana0550 Avatar answered Nov 15 '22 00:11

dana0550