我正在开发一个应用程序,用户可以在视图上放置自己的控件。现在我正在研究我希望控件与某种网格对齐的细节。
提前致谢!
任何可以提供帮助的人?
答案 0 :(得分: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];
}
}
当拖放其中一个对象时,它们必须与网格对齐:
- (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];
}