问题描述
我已经在网上搜索了很长时间,但没有找到使图像视图可拖动的具体方法.这是我到目前为止的内容:
I have been searching the net for a long time and I have not found a concrete way of making an image view draggable. Here is what I have so far:
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类.
MyRect
right now is an empty UIImageView Class.
将图像从微米级的[532,589]
点拖动到屏幕上完全不同的部分,例如[144, 139]
Dragging the image from a point such as [532,589]
on micron moves it to a totally different part of the screen such as [144, 139]
推荐答案
只需在您的视图上附加一个UIPanGestureRecognizer
.在识别器的操作中,基于识别器的平移"(偏移量)更新视图的中心,然后将识别器的平移重置为零.这是一个示例:
Just attach a UIPanGestureRecognizer
to your view. In the recognizer's action, update your view's center based on the "translation" (offset) of the recognizer, then reset the recognizer's translation to zero. Here's an example:
- (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];
}
这篇关于创建可拖动的图像视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!