创建可拖动的图像视图

时间:2013-01-03 23:36:20

标签: objective-c uiimageview position touchesmoved

我一直在网上搜索很长时间,但我还没有找到一种使图像视图可拖动的具体方法。以下是我到目前为止的情况:

tempViewController.h

#import <UIKit/UIKit.h>
#import "MyRect.h"
@class UIView;
@interface tempViewController : UIViewController

@property (nonatomic, strong) MyRect *rect1;
@end

tempViewController.m

#import "tempViewController.h"

@interface tempViewController ()

@end

@implementation tempViewController

@synthesize rect1 = _rect1;

- (void)viewDidLoad
{
    [super viewDidLoad];

    _rect1 = [[MyRect alloc]initWithFrame:CGRectMake(150.0, 100.0, 80, 80)];
    [_rect1 setImage:[UIImage imageNamed:@"cloud1.png"]];
    [_rect1 setUserInteractionEnabled:YES];
    [self.view addSubview:_rect1];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view] == _rect1)
    {
        CGPoint pt = [[touches anyObject] locationInView:_rect1];
        NSLog(@"%@",NSStringFromCGPoint(pt));
        _rect1.center = pt;
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view] == _rect1)
    {
        CGPoint pt = [[touches anyObject] locationInView:_rect1];
        NSLog(@"%@",NSStringFromCGPoint(pt));
        _rect1.center = pt;
    }
}


@end

MyRect现在是一个空的UIImageView类。

将图像从像[532,589]这样的点拖动到微米上会将其移动到屏幕的完全不同的部分,例如[144, 139]

2 个答案:

答案 0 :(得分:3)

只需在您的视图中附加UIPanGestureRecognizer即可。在识别器的操作中,根据识别器的“转换”(偏移)更新视图的中心,然后将识别器的转换重置为零。这是一个例子:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *draggableView = [[UIView alloc] initWithFrame:CGRectMake(150, 100, 80, 80)];
    draggableView.userInteractionEnabled = YES;
    draggableView.backgroundColor = [UIColor redColor];
    [self.view addSubview:draggableView];

    UIPanGestureRecognizer *panner = [[UIPanGestureRecognizer alloc]
        initWithTarget:self action:@selector(panWasRecognized:)];
    [draggableView addGestureRecognizer:panner];
}

- (void)panWasRecognized:(UIPanGestureRecognizer *)panner {
    UIView *draggedView = panner.view;
    CGPoint offset = [panner translationInView:draggedView.superview];
    CGPoint center = draggedView.center;
    draggedView.center = CGPointMake(center.x + offset.x, center.y + offset.y);

    // Reset translation to zero so on the next `panWasRecognized:` message, the
    // translation will just be the additional movement of the touch since now.
    [panner setTranslation:CGPointZero inView:draggedView.superview];
}

答案 1 :(得分:0)

请勿使用-touchesBegan:withEvent:等。

您希望用于此类“高级”内容的是UIGestureRecognizers

您可以在视图中添加一个平移手势识别器设置一个委托(可能是视图本身),然后在回调中将视图移动识别器移动的距离。

您要么记住初始位置并且每次都按-translationInView移动,要么只是按翻译移动,然后使用-setTranslation:inView:将识别器转换重置为零,这样下次调用时委托方法,你将再次获得自上次通话以来的动作。