iOS 拖动手势
@interface ViewController ()
{
UIImageView * imageView; 要拖动的图片
CGPoint begin; 纪录开始拖动点
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
imageView.image =[UIImage imageNamed:@"1"];
[self.view addSubview:imageView];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
begin=[touch locationInView:imageView];开始点
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch =[touches anyObject];
CGPoint last =[touch locationInView:imageView];移动点
float offsetX=last.x-begin.x;
float offsetY=last.y-begin.y;
imageView.center=CGPointMake(imageView.center.x+offsetX, imageView.center.y+ offsetY);
}
}
第二种
UIPanGestureRecognizer * panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self
action:@selector(doHandlePanAction:)];
[self.vLight addGestureRecognizer:panGestureRecognizer];
注:vLight就是要加入拖动的View子类。
- (void) doHandlePanAction:(UIPanGestureRecognizer *)paramSender{
CGPoint point = [paramSender translationInView:self.view];
NSLog(@"X:%f;Y:%f",point.x,point.y);
paramSender.view.center = CGPointMake(paramSender.view.center.x + point.x, paramSender.view.center.y + point.y);
[paramSender setTranslation:CGPointMake(0, 0) inView:self.view];
}
第三者
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch =[touches anyObject];
// lastPoint=[touch locationInView:self.helloWorldLabel];
CGPoint point =[touch locationInView:self.helloWorldLabel];
CGPoint Ppoint =[touch locationInView:self.helloWorldLabel];
float x= point.x-Ppoint.x;
float y= point.y-Ppoint.y;
self.helloWorldLabel.center=CGPointMake(self.helloWorldLabel.center.x+x, self.helloWorldLabel.center.y+y);
}

浙公网安备 33010602011771号