0

我已经在网上搜索了很长时间,但我还没有找到一种使图像视图可拖动的具体方法。这是我到目前为止所拥有的:

临时视图控制器.h

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

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

临时视图控制器.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]

4

2 回答 2

3

只需将 a 添加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];
}
于 2013-01-03T23:49:14.037 回答
0

不要使用-touchesBegan:withEvent:等。

您想要用于此类“高级”事物的是UIGestureRecognizers.

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

您要么记住初始位置并-translationInView每次移动,要么只是按平移移动,然后使用-setTranslation:inView:将识别器平移重置为零,因此在下一次调用委托方法时,您将再次获得自上次调用以来的移动.

于 2013-01-03T23:46:07.293 回答