如何对齐组件并网?(How to align components to grid?)

2019-08-31 21:23发布

我工作的一个应用程序,用户可以把一个视图自己的控制。 现在我的工作,我想控件对齐到一种网格的细节。

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

提前致谢!

任何人谁可以帮忙吗?

Answer 1:

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

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

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

}



文章来源: How to align components to grid?