如何将组件对齐到网格? [英] How to align components to grid?

查看:38
本文介绍了如何将组件对齐到网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个用户可以在视图上放置自己的控件的应用程序.现在我正在处理希望控件与某种网格对齐的细节.

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.

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

提前致谢!

谁能帮忙?

推荐答案

对于那些仍然对答案感兴趣的人:

For those who are still interested in the answer:

我先画了横竖线:

-(void)drawGrid{

-(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{

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

}

这篇关于如何将组件对齐到网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆