I'm working on an application where users can put their own controls on a view. Now I'm working on the details where I want the controls to be aligned to a sort of grid.
- How can I draw a grid?
- How can I make sure the controls are aligned automatically to the grid (to the closest corner?)
Thanks in advance!
anyone who can help?
For those who are still interested in the answer:
I first drew the horizontal and vertical line:
-(void)drawGrid
{
for(int y=self.gridSize;y<self.templateEditView.frame.size.height;y+=self.gridSize){
UIView *hline = [[UIView alloc] init];
[hline setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.1f]];
hline.frame = CGRectMake(0, y, self.templateEditView.frame.size.width, 1);
[self.templateEditView addSubview:hline];
}
for(int x=self.gridSize;x<self.templateEditView.frame.size.width;x+=self.gridSize){
UIView *vline = [[UIView alloc] init];
[vline setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.1f]];
vline.frame = CGRectMake(x, 0, 1, self.templateEditView.frame.size.height);
[self.templateEditView addSubview:vline];
}
}
When one of the objects is dragged and dropped, They have to align to the grid:
-(void)alignToGrid:(UIView *)control{
int gridSize = self.gridSize;
int oldX = (int)control.frame.origin.x;
int newX = (oldX /gridSize)*gridSize;
if(oldX%gridSize > gridSize/2){
newX+=gridSize;
}
int oldY = (int)control.frame.origin.y;
int newY = (oldY /gridSize)*gridSize;
if(oldY%gridSize > gridSize/2){
newY+=gridSize;
}
[UIView animateWithDuration:0.3f delay:0.0f options:UIViewAnimationOptionCurveLinear animations:^ {
[control setFrame: CGRectMake(newX,newY,control.frame.size.width,control.frame.size.height)];
} completion:nil];
}