UIPanGestureRecognizer

平移手势识别器检测拖动手势。以下示例将图像添加到视图控制器,并允许用户在屏幕上拖动它。

Objective-C

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"imageToDrag"]];
    [imageView sizeToFit];
    imageView.userInteractionEnabled = YES;
    [self.view addSubview:imageView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [imageView addGestureRecognizer:pan];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer {
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointZero inView:self.view];
}

迅速

override func viewDidLoad() {
    super.viewDidLoad()
    
    let imageView = UIImageView.init(image: UIImage.init(named: "imageToDrag"))
    imageView.sizeToFit()
    imageView.isUserInteractionEnabled = true
    self.view.addSubview(imageView)
    
    let pan = UIPanGestureRecognizer.init(target: self, action: #selector(handlePan(recognizer:)))
    imageView.addGestureRecognizer(pan)
}

func handlePan(recognizer: UIPanGestureRecognizer) {
    let translation = recognizer.translation(in: self.view)
    if let view = recognizer.view {
        view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
    }
    recognizer.setTranslation(CGPoint.zero, in: self.view)
}

注意: 虽然 UIPanGestureRecognizer 对于检测任何拖动手势很有用,但如果你只想检测基本手势,例如用户向左/向右或向上/向下拖动手指,请使用 UISwipeGestureRecognizer。如果你需要访问 translationInView:velocityInView:等方法,UIPanGestureRecognizer 是更好的选择。