使用pangesture在父视图中移动UIView

时间:2016-12-08 05:39:29

标签: ios objective-c

我想在父视图中移动视图我正在使用UIPanGestureRecognizer来移动视图。我正在使用下面的代码。

-(void)move:(UIPanGestureRecognizer *)recognizer {
    CGPoint touchLocation = [recognizer locationInView:self.customeView];

    self.view.center = touchLocation;
}

我想使用locationInView来移动视图而不是translationInView。任何人都可以帮助我如何使用locationInView在父视图中移动视图?

1 个答案:

答案 0 :(得分:3)

您使用UIPanGestureRecognizer走在正确的轨道上。您可能错过了开始和结束手势状态处理。这是一个完整的解决方案,我只是在示例项目(Swift)中将panView作为视图控制器根视图的子类。

class ViewController: UIViewController {

    @IBOutlet weak var panView: UIView!

    // records the view's center for use as an offset while dragging
    var viewCenter: CGPoint!

    override func viewDidLoad() {
        super.viewDidLoad()
        panView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.dragView)))
    }

    func dragView(gesture: UIPanGestureRecognizer) {
        let target = gesture.view!

        switch gesture.state {
        case .began, .ended:
            viewCenter = target.center
        case .changed:
            let translation = gesture.translation(in: self.view)
            target.center = CGPoint(x: viewCenter!.x + translation.x, y: viewCenter!.y + translation.y)
        default: break
        }
    }

}