升级到Swift 3.0后,从左到右的动画无法正常工作

时间:2016-10-07 20:33:36

标签: swift swift3 caanimation

所以我刚从2.3升级到Swift 3.0。关于我的项目的其他所有内容都很好,除了这行代码及其错误:

        if let delegate: AnyObject = completionDelegate {
        leftToRightTransition.delegate = delegate //ERROR MESSAGE
    }

错误消息显示:

  

无法将“AnyObject”类型的值指定为类型CAAnimation

以下是完整相关的代码块。本质上这个代码就是动画。在我的项目的其他地方(我肯定与问题没有关系,但只是针对上下文)的代码允许用户刷过图像数组。这个块是它的动画部分('轻扫'动画'):

extension UIView {
func rightToLeftAnimation(_ duration: TimeInterval = 0.5, completionDelegate: AnyObject? = nil) {
    // Create a CATransition object
    let rightToLeftTransition = CATransition()

    // Set its callback delegate to the completionDelegate that was provided
    if let delegate: AnyObject = completionDelegate {
        rightToLeftTransition.delegate = delegate //ERROR MESSAGE ON THIS LINE
    }

    rightToLeftTransition.type = kCATransitionPush
    rightToLeftTransition.subtype = kCATransitionFromLeft
    rightToLeftTransition.duration = duration
    rightToLeftTransition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    rightToLeftTransition.fillMode = kCAFillModeRemoved

    // Add the animation to the View's layer
    self.layer.add(rightToLeftTransition, forKey: "rightToLeftTransition")
}

这在Swift 2.3中运行得很好,但现在它不起作用。像这样的小东西让我疯了......任何帮助都会受到赞赏;)

2 个答案:

答案 0 :(得分:1)

现在是CAAnimationDelegate

if let delegate = completionDelegate as? CAAnimationDelegate {
    rightToLeftTransition.delegate = delegate
}

或者只是:

func rightToLeftAnimation(_ duration: TimeInterval = 0.5, completionDelegate: CAAnimationDelegate? = nil) {
    // Create a CATransition object
    let rightToLeftTransition = CATransition()

    // Set its callback delegate to the completionDelegate that was provided
    rightToLeftTransition.delegate = completionDelegate

    rightToLeftTransition.type = kCATransitionPush
    rightToLeftTransition.subtype = kCATransitionFromLeft
    rightToLeftTransition.duration = duration
    rightToLeftTransition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    rightToLeftTransition.fillMode = kCAFillModeRemoved

    // Add the animation to the View's layer
    layer.add(rightToLeftTransition, forKey: "rightToLeftTransition")
}

答案 1 :(得分:0)

Try this , Its working in my code:

 let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipedRight))
        swipeRight.direction = .right
        SLIDEVIEW.addGestureRecognizer(swipeRight)


        let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.swipedLeft))
        swipeLeft.direction = .left
        SLIDEVIEW.addGestureRecognizer(swipeLeft)

func swipedRight()
    {
        print("swiped right")
        updateFrames(towards: "right")
    }

    func swipedLeft()
    {
        print("swiped left")
        updateFrames(towards: "left")
    }