如何在不重叠视图的情况下拖动uiimageview?

时间:2013-01-31 07:23:51

标签: ios drag-and-drop uiimageview

我在superview中有多个视图。如何在不重叠或触摸其他视图的情况下拖动uiimageview。任何帮助表示赞赏..

1 个答案:

答案 0 :(得分:1)

我已经实施了类似的东西。我在这里发布代码片段。 Draggable是您需要在包含图像的其他类中导入的类。

1)Draggable.h

#import <UIKit/UIKit.h>

@interface Draggable : UIImageView
{
    CGPoint startLocation;
}
@end

2)Draggable.m

#import "Draggable.h"

@implementation Draggable

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    // Retrieve the touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    // Move relative to the original touch point
    CGPoint pt = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [self setFrame:frame];
}

@end

3)ProfilePicViewController.m - 我的带图像的类

#import "Draggable.h"

UIImageView *dragger;

-(void)viewWillAppear:(BOOL)animated
{
    UIImage *tmpImage = [UIImage imageNamed:@"icon.png"];

    CGRect cellRectangle;
    cellRectangle = CGRectMake(0,0,tmpImage.size.width ,tmpImage.size.height );
    dragger = [[Draggable alloc] initWithFrame:cellRectangle];
    [dragger setImage:tmpImage];
    [dragger setUserInteractionEnabled:YES];

    [self.view addSubview:dragger];

}

在这里你可以在其他图像上拖动“拖动器”。确保图像尺寸合适。 icon.png的大小是48X48。所以只需要适合您屏幕的图像大小。

希望这可以帮助你。