平移手势识别器可检测到拖动手势。以下示例将图像添加到视图控制器,并允许用户在屏幕上四处拖动图像。
目标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。UIPanGestureRecognizer如果您需要访问诸如translationInView:或的方法,则是更好的选择velocityInView:。