2013-04-23 99 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]; 

}