是否可以使用UIPanGestureRecognizer将顶视图拖到右侧以显示子视图

时间:2017-07-18 12:42:06

标签: ios swift uipangesturerecognizer

我需要拖动我来查看右边屏幕宽度的2/3部分以显示子视图(包含一个tableview),然后在与tableview交互后将其拖回来。

UIPanGestureRecognizer似乎是我需要的,但在阅读Apple的文档后,我无法弄清楚swift所需的代码。

所以要澄清一下 - 我有一个捕获用户数据的视图,我有一个包含电话标签和数字的tableview - 我希望能够拖动用户视图,公开表然后拖动用户回顾。

@IBAction func panPiece(_ gestureRecognizer : UIPanGestureRecognizer) {
    // Move the anchor point of the view's layer to the touch point
    // so that moving the view becomes simpler.
    let piece = gestureRecognizer.view
    self.adjustAnchorPoint(gestureRecognizer: gestureRecognizer)

    if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
        // Get the distance moved since the last call to this method.
        let translation = gestureRecognizer.translation(in: piece?.superview)

        // Set the translation point to zero so that the translation distance
        // is only the change since the last call to this method.
        piece?.center = CGPoint(x: ((piece?.center.x)! + translation.x),
                                y: ((piece?.center.y)! + translation.y))
        gestureRecognizer.setTranslation(CGPoint.zero, in: piece?.superview)
    }
}
func adjustAnchorPoint(gestureRecognizer : UIGestureRecognizer) {
    if gestureRecognizer.state == .began {
        let view = gestureRecognizer.view
        let locationInView = gestureRecognizer.location(in: view)
        let locationInSuperview = gestureRecognizer.location(in: view?.superview)

        // Move the anchor point to the touch point and change the position of the view
        view?.layer.anchorPoint = CGPoint(x: (locationInView.x / (view?.bounds.size.width)!),
                                          y: (locationInView.y / (view?.bounds.size.height)!))
        view?.center = locationInSuperview
    }
}

1 个答案:

答案 0 :(得分:1)

用于附加带有视图的手势

 let panGesture = UIPanGestureRecognizer(target: self, action:#selector(handlePanGesture))
 @objc private func handlePanGesture(sender:UIPanGestureRecognizer)
 {
     var translation = sender.translation(in: self)
     sender.view?.superview?.bringSubview(toFront: sender.view!)
     sender.view?.center = CGPoint(x: (sender.view?.center.x)! + translation.x , y : (sender.view?.center.y)! + translation.y)
     sender.setTranslation(CGPoint.zero, in: self)
 }