如何通过向下拖动关闭UITableViewController(平移)

时间:2015-10-25 22:47:05

标签: ios swift uipangesturerecognizer

我正在制作iOS应用程序。

现在我坚持做以下事情。

  • 详细信息屏幕弹出为模态屏幕
  • 用户希望通过像Twitter的照片屏幕一样向下拖动来关闭模态窗口

我试图通过引用How to use UIPanGestureRecognizer to move object? iPhone/iPad

进行编码

我的代码如下所示。 它使tableView向奇怪的方向移动,然后关闭模态。

var firstX: CGFloat = 0
var firstY: CGFloat = 0
var finalX: CGFloat = 0
var finalY: CGFloat = 0

override func viewDidLoad() {
    super.viewDidLoad()
    let recognizer : UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "move:")
    recognizer.minimumNumberOfTouches = 1
    recognizer.maximumNumberOfTouches = 1
    self.tableView.addGestureRecognizer(recognizer)
}

func move(sender : UIPanGestureRecognizer) {
    print("move")

    self.view.bringSubviewToFront(tableView)
    var translatedPoint : CGPoint = sender.translationInView(self.view)
    if sender.state == UIGestureRecognizerState.Began {
        firstX = 0 // (sender.view?.center.x)!
        firstY = (tableView?.center.y)!
    }
    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY)
    tableView?.center = translatedPoint

    if sender.state == UIGestureRecognizerState.Ended {
        let velocityY = 0.2 * sender.velocityInView(self.view).y
        finalX = firstX //translatedPoint.x + velocityX
        finalY = translatedPoint.y + velocityY

        if (UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) {

            if finalY < 0 {
                finalY = 0
            } else if finalY > 1024 {
                finalY = 1024
            }

        } else {

            if finalY < 0 {
                finalY = 0
            } else if finalY > 768 {
                finalY = 1024
            }
        }

        let animationDuration = ( abs(velocityY) * 0.0002 ) + 0.2

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDuration(Double(animationDuration))
        UIView.setAnimationCurve(UIViewAnimationCurve.EaseOut)
        UIView.setAnimationDelegate(self)
        UIView.setAnimationDidStopSelector("animationDidFinish")
        self.view.center = CGPointMake(finalX, finalY)
        UIView.commitAnimations()


    }
}

func animationDidFinish() {
    print("animationDidFinish")
    if finalY > 50 {
        self.dismissViewControllerAnimated(true, completion: nil)
    }

}

有没有人指出我正确的方向? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要创建自定义模态动画。您应该从Customizing the Transition AnimationsPresentation and Transitions部分阅读View Controller Programming Guide for iOS

具体而言,Adding Interactivity to Your Transitions上有一部分,但您可能需要阅读的内容不仅仅是要理解的部分。

简而言之,您必须创建UIViewControllerTransitioningDelegate的实现,并将其分配给正在呈现的视图控制器的转换委托。 UIViewControllerTransitioningDelegate的工作是将许多其他对象出售给UIKit,以处理用于呈现和解除视图控制器的自定义动画(以及可选的演示)。

除了UIViewControllerTransitioningDelegate的实施,您还必须创建UIViewControllerAnimatedTransitioningUIViewControllerInteractiveTransitioning的实施。这些对象最终将是执行相关动画的对象,它们是UIViewControllerTransitioningDelegate实现提供给UIKit的对象。