简体   繁体   English

如何在 UIImageViews 之间拖放和居中图像?

[英]How do I drag & drop and center an image between UIImageViews?

I am developing a chess app and currently I have a simple setup: background of the board and UIImageView for all the cells.我正在开发一个国际象棋应用程序,目前我有一个简单的设置:棋盘的背景和所有单元格的 UIImageView。 So far I have managed to successfully drag & drop images around the board with the use of UITouch and CGPoint.到目前为止,我已经成功地使用 UITouch 和 CGPoint 在板上拖放图像。

My problem is that I can drag & drop these images anywhere in my app and I need to create code to set boundaries on both the board and the images.我的问题是我可以在我的应用程序中的任何位置拖放这些图像,我需要创建代码来设置电路板和图像的边界。 Right now my images can be dragged and dropped on top of each other, or in between cells when they need to be dropped within them, or they can be dropped outside the bounds of the board where they need to be within its bounds.现在,我的图像可以拖放到彼此的顶部,或者在需要将它们放入单元格之间时拖放到单元格之间,或者可以将它们放到需要在其边界内的电路板边界之外。 Therefore this is an issue of setting boundaries.因此,这是一个设置边界的问题。

Code for handling drag & drop events:处理拖放事件的代码:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];

    CGPoint touchLocation = [touch locationInView:[self view]];   

    for (UIImageView *piece in chessCells) {
        if([touch view] == piece){
            piece.center = touchLocation;
        }
    }

}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [self touchesBegan:touches withEvent:event];
}

About the for loop :关于for 循环

All the cells in my board are blank IBOutlets with UIImageViews, which I organize by keeping them in a NSArray called 'chessCells'.我板上的所有单元格都是带有 UIImageViews 的空白 IBOutlets,我通过将它们保存在一个名为“chessCells”的 NSArray 中进行组织。 I have a method that displays the images in their respective cells when the app starts.我有一种方法可以在应用程序启动时在各自的单元格中显示图像。 From this point I am be able to grab them and move them around freely across the chessboard... but as I have found, a bit too freely.从这一点上,我能够抓住它们并在棋盘上自由移动它们......但正如我发现的那样,有点太自由了。

You should try with CGRectIntersectRect add this to your code您应该尝试使用CGRectIntersectRect将此添加到您的代码中

if (CGRectIntersectsRect(yourImgFrame1, yourImgFrame2)) {
    //do What ever you want
}

with this code when your yourImgFrame1 intersects yourImgFrame2 you can perform any action使用此代码,当yourImgFrame1yourImgFrame2相交时,您可以执行任何操作

Good Luck祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM