我正在开发一个棋盘游戏,我的棋盘上有 10x10 个单元格,每个单元格都由一个 UIImageView 获取,所以当玩家试图将一个棋子放入单元格时,相应的单元格应该设置为图像。
我想要实现的是,当用户拖动一 block 并尝试将其放到板上时,该 block 应该适合单元格的 UIImageView。现在的问题是我可以把棋子放在棋盘上的任何地方,甚至可以放在两个单元格之间。我能做些什么来修复它?谢谢
----------------更新:----------------
由于我在 Storyboard 中完成了所有工作,所以我可以分享的代码非常少。我在 .h 文件中有以下代码行:
@property(retain) IBOutletCollection(UIImageView) NSArray *images;
它们是一个长度为100的UIImageView数组,每一个对应图板中的一个cell,如下所示:
当前板上的图标是自动生成的,我想拖到板上的目标图标位于板的左上角(“X”图标)。以及以下处理拖动的方法:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
现在的问题是我可以将“X”放在板上的任何位置,如下所示:
但我想将它放入电路板的一个单元格中。
最佳答案
您可以通过检测翻译结束于哪个单元格来实现这一点。例如:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
CGPoint origin = yourGrid.frame.origin; //where yourGrid refers to the main game board
float cellHeight = 30; //enter the corresponding value for cellHeight and cellWidth
float cellWidth = 30; //I've chosen 30 as an arbitrary value.
int translationXIndex = (recognizer.view.center.x + translation.x - origin.x)/cellWidth;
int translationYIndex = (recognizer.view.center.y + translation.y - origin.y)/cellHeight;
//Assuming you count left to right and then up to down
[[images objectAtIndex: (translationXIndex + (10*translationYIndex))] setImage:[UIImage imageNamed:@"YourImage.png"]];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
//You would have to remove the object you just dragged now, since you've changed the image of the corresponding cell
}
这是如何工作的:识别器寻找翻译的中心并找出它位于哪个单元格中。然后它访问该单元格的 imageView 并将图像更改为目标图像。
希望这对您有所帮助。
关于ios - 拖动图像以适合正确的边界框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22677104/