我正在尝试将自定义segue动画添加到我的应用中,但始终收到此错误:
无法将类型“ SlideAnimation.Type”的值分配给类型“ UIViewControllerTransitioningDe”
我的ViewController代码:
import UIKit
class ViewController: UIViewController{
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
destination.transitioningDelegate = SlideAnimation
}
}
我的SlideAnimation.swift代码:
import UIKit
class SlideAnimation: NSObject,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate {
let duration = 0.5
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) else{
return
}
let container = transitionContext.containerView
let screenOffUp = CGAffineTransform(translationX: 0, y: -container.frame.height)
let screenOffDown = CGAffineTransform(translationX: 0, y:container.frame.height)
container.addSubview(fromView)
container.addSubview(toView)
toView.transform = screenOffUp
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.8, options: [], animations: {
fromView.transform = screenOffDown
fromView.alpha = 0.5
toView.transform = CGAffineTransform.identity
toView.alpha = 1
}) {(success) in
transitionContext.completeTransition(success)
}
}
}
}
我也是Xcode和这个网站的新手,如果还不清楚的话,对不起。
最佳答案
该问题是由以下行引起的:
destination.transitioningDelegate = SlideAnimation
您需要传递一个符合
UIViewControllerTransitioningDelegate
的类的实例,但是您要传递一个类的名称。您需要创建
SlideAnimation
的实例并将其设置为委托:destination.transitioningDelegate = SlideAnimation()
但这实际上会引起一个新问题,因为
transitioningDelegate
是弱引用,并将立即变为nil
。您需要创建对SlideAnimation
实例的强引用。import UIKit
class ViewController: UIViewController{
let transitionDelegate = SlideAnimation()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination
destination.transitioningDelegate = transitionDelegate
}
}
关于ios - 无法将类型“SlideAnimation.Type”的值分配给类型“UIViewControllerTransitioningDelegate”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49681872/