0

我正在创建一个应用程序,用户可以在其中使用那里的图像设计自己的舞台。我已经将按钮创建为图像,现在我想要一些代码,使用户能够将图像(按钮)拖放到特定的图像视图区域中。

4

1 回答 1

0

您可以通过点击手势来实现这一点(例如点击第一个图像视图,点击目标图像视图),但这不是很直观。使用 UIPanGestureRecognizer 进行适当的拖放对于您的最终用户来说将更加直观。

从技术上讲,您不是从图像视图中拖动图像,而是实际上是在拖动图像视图本身。(如果没有图像视图,图像本身就没有视觉表示。)当您放手时,您将动画化图像视图帧的变化以完成错觉。

如果你有一个 NSArray 的 imageViews,你可以给他们的 superview 添加一个手势:

@property (nonatomic, strong) NSMutableArray *imageViews;

- (void)viewDidLoad
{
[super viewDidLoad];

[self createImageViewArray];

UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self                                                                          action:@selector(handlePan:)];
[self.view addGestureRecognizer:gesture];
}

- (void)createImageViewArray
{
self.imageViews = [NSMutableArray array];
}

- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static UIImageView *draggedImage = nil;
static CGRect draggedImageOriginalFrame;

CGPoint location = [gesture locationInView:gesture.view];

if (gesture.state == UIGestureRecognizerStateBegan)
{

    draggedImage = [self determineImageForLocation:location];

    if (draggedImage)
    {
        draggedImageOriginalFrame = draggedImage.frame;
        [draggedImage.superview bringSubviewToFront:draggedImage];
    }
}
else if (gesture.state == UIGestureRecognizerStateChanged && draggedImage != nil)
{

    CGPoint translation = [gesture translationInView:gesture.view];
    CGRect frame = draggedImageOriginalFrame;
    frame.origin.x += translation.x;
    frame.origin.y += translation.y;
    draggedImage.frame = frame;
}
else if (draggedImage != nil && (gesture.state == UIGestureRecognizerStateEnded ||
                                 gesture.state == UIGestureRecognizerStateCancelled ||
                                 gesture.state == UIGestureRecognizerStateFailed))
{

    UIImageView *droppedOver = nil;

    if (gesture.state == UIGestureRecognizerStateEnded)
        droppedOver = [self draggedImageView:draggedImage toLocation:location];

    if (droppedOver == nil)
    {
        [UIView animateWithDuration:0.25
                         animations:^{
                             draggedImage.frame = draggedImageOriginalFrame;
                         }];
    }
    else
    {
        [droppedOver.superview bringSubviewToFront:droppedOver];

        [UIView animateWithDuration:0.25
                         animations:^{
                             draggedImage.frame = droppedOver.frame;
                             droppedOver.frame = draggedImageOriginalFrame;
                         }];
    }
  }
 }

- (UIImageView *)draggedImageView:(UIImageView *)draggedView toLocation:(CGPoint)location
{
   for (UIImageView *imageview in self.imageViews)
     if (CGRectContainsPoint(imageview.frame, location) && imageview != draggedView)
        return imageview;

 return nil;
}
- (UIImageView *)determineImageForLocation:(CGPoint)location
{
 return [self draggedImageView:nil toLocation:location];
}
于 2013-07-24T07:20:46.930 回答