一、预览
话不多说,直接上图:
二、代码解析
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *dragView;//可以是UIView的子类
@property (nonatomic, strong) UIPanGestureRecognizer *panGestureRecognizer;//添加在视图上的拖动手势
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.dragView addGestureRecognizer:self.panGestureRecognizer];
}
- (UIPanGestureRecognizer *)panGestureRecognizer
{
if (!_panGestureRecognizer) {
_panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragViewMoved:)];
}
return _panGestureRecognizer;
}
- (void)dragViewMoved:(UIPanGestureRecognizer *)panGestureRecognizer
{
if (panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [panGestureRecognizer translationInView:self.view];
self.dragView.center = CGPointMake(self.dragView.center.x + translation.x, self.dragView.center.y + translation.y);
//关键,不设为零会不断递增,视图会突然不见
[panGestureRecognizer setTranslation:CGPointZero inView:self.view];
}
}