2013-04-23 47 views
0

我正在研究一个应用程序,用户可以将自己的控件放在视图上。现在我正在处理我希望控件与某种网格对齐的细节。如何将组件对齐到网格?

  1. 如何绘制网格?
  2. 我怎样才能确保控件会自动与网格对齐(到最近的角落?)

提前感谢!

任何人都可以帮忙吗?

回答

0

对于那些谁仍然有兴趣在回答:

我第一次画的水平和垂直线:

- (无效)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]; 
} 

}

当其中一个对象被拖放时,它们必须与网格对齐:

- (无效)alignToGrid:(UIView的*)控制{

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]; 

}