我正在尝试在TabBar中的选项卡之间实现交互式动画过渡。我正在使用平移手势识别器。我制作了一个自定义动画,并使用UIPercentDrivenInteractiveTransition使切换交互。但似乎我并不真正理解所有动画背后的过程 我确实设法制作了一个非交互式动画,但添加交互性在某种程度上是困难的。我在互联网上阅读了很多教程,并且我完全理解每个人发布的代码片段是如何工作的,但我在某种程度上无法实现它。我制作了一个TabBar应用程序,其中包含两个带导航栏的选项卡 这是我的代码:
TabBarController.swift
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
var usingGesture = false
var interactiveTransition:UIPercentDrivenInteractiveTransition?
override func viewDidLoad() {
super.viewDidLoad()
let panGesture = UIPanGestureRecognizer(target: self, action: "didPan:")
self.view.addGestureRecognizer(panGesture)
self.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tabBarController(tabBarController: UITabBarController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return self.interactiveTransition
}
func didPan(gesture: UIPanGestureRecognizer){
let point = gesture.locationInView(gesture.view)
let percent = fmax(fmin((point.x / 300.0), 0.99), 0.0)
self.interactiveTransition = UIPercentDrivenInteractiveTransition()
switch (gesture.state){
case .Began:
self.usingGesture = true
self.selectedIndex++
case .Changed:
self.interactiveTransition?.updateInteractiveTransition(percent)
case .Ended, .Cancelled:
if percent > 0.5 {
self.interactiveTransition?.finishInteractiveTransition()
} else {
self.interactiveTransition?.cancelInteractiveTransition()
}
self.usingGesture = false
default:
NSLog("Unhandled state")
}
}
}
TransitionToLeft.swift
import UIKit
class TransitionToLeft: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning {
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromView:UIView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView:UIView = transitionContext.viewForKey(UITransitionContextToViewKey)!
transitionContext.containerView().addSubview(fromView)
transitionContext.containerView().addSubview(toView)
toView.frame = CGRectMake(toView.frame.width, 0, toView.frame.width, toView.frame.height)
let fromNewFrame = CGRectMake(-1 * fromView.frame.width, 0, fromView.frame.width, fromView.frame.height)
UIView.animateWithDuration( 0.7, animations:{ () -> Void in
toView.frame = fromView.frame
fromView.frame = fromNewFrame
},{ (Bool) -> Void in
// update internal view - must always be called
transitionContext.completeTransition(true)
})
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.7
}
}
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
我认为您的问题出在手势识别器中。尝试将其添加到self.selectedViewController.view
而不是self.view
。
此外,您的代码有误:我认为self.interactiveTransition = UIPercentDrivenInteractiveTransition()
应为self.interactiveTransition = TransitionToLeft()
。