如何通过点击而不是拖放来在不同的UIView之间移动不同的UIImages

时间:2012-05-29 14:35:31

标签: objective-c xcode drag-and-drop uiimageview uiimage

我正在使用Xcode开发一个项目,我使用一堆包含UIImages的小UIImageViews设置了一个棋盘,并将它们放在一个更大的UIImageView中,代表棋盘。

到目前为止,我设法正确地使用UITouches在棋盘上自由地拖放UIImageViews(棋子)。然而,当我放下它们时,它们只会放在我释放它们的任何地方,自然应该如此,但这不是我想要的预期效果。

理想情况下,UIImageViews不应该移动到任何地方,我只想将UIImage从当前选择的UIImageView传输到下一个UIImageView。我相信不以这种方式拖放会更简单,但我会使用点击(或点击)。我点击UIImageView,然后点击下一步,UIImageView将从之前的UIImageView获取UIImage。想想你如何在没有拖放图像的情况下下棋。

那么有没有人对如何在这里进行任何建议?提前谢谢!

编辑:这里有一些代码来展示我现在正在做的事情:

//================================================================================
// I have two arrays containing UIImageViews each, one representing board cells,
// the other one the pieces. The below functions handle the touch and drag actions.
// What I need to do is change this somehow so that the UIImageViews representing
// the pieces do one of the following things:
// 1. When the pieces are dragged, you can drop them and they center themselves
//    on top of the UIImage views that represent the cells of the board.
// 2. I have an array of UIImageViews containing the cells, when I click on a
//    UIImageView that has the image of a piece, it is copied and pasted onto
//    the next UIImageView that I click, of course controls will be set to determine
//    a valid move I can handle doing this part.
//================================================================================

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //get location of the current touch event
    UITouch *touch = [[event allTouches] anyObject];
    //get touch location for the touched image (self used instead of touch)
    CGPoint touchLocation = [touch locationInView:[self view]];   
    //select and give current location to the selected view
    for (UIImageView *piece in chessCells) {
        if([touch view] == piece){
            piece.center = touchLocation;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    //allow the selected event (in our case a UIImageView) to be dragged
    [self touchesBegan:touches withEvent:event];
}

最初我把这个问题保持开放,因为我知道我必须以某种方式改变我的实现,但我希望这段代码有助于理解我面临的问题:拖放任何地方没有任何限制,我只是不知道如何控制这种情况发生。

2 个答案:

答案 0 :(得分:1)

当UIImageView上的点击发生时,如何制作它的副本,并使用该副本进行拖动。当发布完成后,使用复制的UIImageView中的UIImage来更改被删除的UIImageView,然后删除复制的UIImageView?

答案 1 :(得分:1)

UIImage只是数据 - 它不会在任何地方绘制自己。您需要一个UIImageView(或其他一些视图或图层类)来在屏幕上绘制图像。因此,如果您只是将图像从一个图像视图移动到另一个图像视图,图像将在一个位置消失并出现在另一个位置 - 当一个图形从一个正方形移动到另一个正方形时,将不会有任何动画。

我建议使用Core Animation来移动图像视图。这将提供一些反馈,以便用户更好地了解哪个部分移动到哪里。这在象棋这样的游戏中尤其重要,其中部分挑战是注意哪些棋子可以移动到哪里。

将棋子正确放置在正方形上的关键是将它们移动到所需的位置。例如,您可以通过将相应图像视图的center从一个正方形的中心更改为另一个正方形的中心来移动一块。