我已经阅读了有关拖动和gestureRecognizer
的所有内容,但还没有找到解决方案。
我得到了#34; gamefield" 10x10 我希望通过对齐网格实现拖放,并检查元素是否放置在" gamefield"。
我得到了我的8" TempButtons"使用UIView
添加到action:@selector(imageMoved:withEvent:)
buttonsSuperView。
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
UIControl *control = sender;
originalPosition = [self getButton:sender];
UITouch *touch = [[event allTouches] anyObject];
point = [touch locationInView:control];
float step = 31.0; // Grid step size.
CGPoint center = control.center;
center.x += step * floor((point.x / step));
center.y += step * floor((point.y / step));
control.center = center;
}
它可以工作,我可以用网格步骤31px移动任何按钮。我可以把它放在任何地方,但我必须把它放在UIView
fieldView上。如果它放在那里它没关系,我可以在另一个瓷砖上更换它。但是如果我把它放在fieldView之外,按钮应该返回它的位置。像这样:
if ([self.fieldView pointInside:point withEvent:nil])
{
control.center = center;
} else {
[UIView animateWithDuration:0.4
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^ {
control.center = originalPosition;
// to
}
completion:^(BOOL finished) {}];
}
如果此代码放在- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *)
事件方法上,则会使按钮返回其原始位置"它一直在移动。但是我需要检查一下它是否只适用于触摸的'#s;'。但这是另一种方法,我不明白如何按下按钮及其原始坐标如果放置不当而取回。
也许有更好的方式来使用' UIView'而不是' UIButton'但我仍然不明白该怎么做。
提前致谢。 亲切的问候,
尼克
答案 0 :(得分:4)
由于没有人回答我的问题,我花了一些时间找到了解决方案。
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
dragObject = sender;
originalPosition = [self getButton:sender];
UITouch *touch = [[event allTouches] anyObject];
point = [touch locationInView:dragObject];
float step = 31.0; // Grid step size.
CGPoint center = dragObject.center;
center.x += step * floor((point.x / step));
center.y += step * floor((point.y / step));
dragObject.center = center;
[sender addTarget:self action:@selector(touchesEnded:withEvent:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if (![fieldView pointInside:dragObject.center withEvent:nil])
{
[UIView animateWithDuration:0.4
delay:0.0
options:UIViewAnimationOptionCurveEaseInOut
animations:^ {
dragObject.center = CGPointMake(originalPosition.x + 15.5, originalPosition.y + 15.5);
}
completion:^(BOOL finished) {}];
}
}
现在它像魅力一样,我可以继续前进。我的按钮自由地移动到网格上,当在游戏区外面时,它们会移回原来的位置。
此致 尼克