从tabBarController,我将以模态方式呈现一个新的viewController。我想在其上实现一个panGestureRecognizer,以便用户可以向下拖动viewController来关闭它。但是,我在模态视图控制器中嵌入了一个scrollview,这使得它更加困难。
到目前为止,我的代码是一个非常便宜的解决方案:
override func viewDidLoad() {
pan = UIPanGestureRecognizer(target: self, action: "handlePan:")
self.scrollview.addGestureRecognizer(pan)
self.view.addGestureRecognizer(scrollview.panGestureRecognizer)
}
func handlePan(recognizer:UIPanGestureRecognizer!) {
switch recognizer.state {
case .Changed:
handlePanChanged(recognizer); break
case .Ended:
handlePanTerminated(recognizer); break
case .Cancelled:
handlePanTerminated(recognizer); break
case .Failed:
handlePanTerminated(recognizer); break
default: break
}
}
func handlePanChanged(recognizer:UIPanGestureRecognizer!) {
if let view = recognizer.view {
var translation = recognizer.translationInView(self.view)
println("moving")
view.center = CGPointMake(view.center.x, view.center.y + translation.y);
recognizer.setTranslation(CGPointZero, inView: self.view)
}
}
func handlePanTerminated(recognizer:UIPanGestureRecognizer!) {
if let view = recognizer.view {
let offset = self.view.center.y - view.center.y
let vel = recognizer.velocityInView(self.view).y
if (fabs(offset) > kTriggerDistance) || (fabs(vel) > kTriggerVelocity) {
let pointsToMove = self.pointsToMove(view, angle: 0, direction: vel > 0 ? .Down : .Up)
let animationDuration = NSTimeInterval(min(0.3, pointsToMove / Float(vel)))
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
view.center = CGPointMake(view.center.x, view.center.y + CGFloat(pointsToMove))
}, completion: { (completed) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
view.removeFromSuperview()
})
}
else {
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.75,
initialSpringVelocity: 2.0, options: nil, animations: { () -> Void in
view.center = self.view.center
}, completion: nil);
}
}
}
虽然这允许我拖动scrollView,但我真的不知道如何拖动整个viewController。我是否必须在根视图控制器上将其作为子视图?