UIView.animateWithDuration 不在单独的视图控制器上设置动画

UIView.animateWithDuration doesn't animate on separate view controller

设置动画重复淡入淡出。 'viewSmall' 和 'viewBig' 是 UIImageView。

view storyboard shot

class TestViewController: UIViewController {

    @IBOutlet weak var viewBig: UIImageView!
    @IBOutlet weak var viewSmall: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        animate()
    }

    func animate() {
        UIView.animateWithDuration(0.5,
                                   delay: 0,
                                   options: [.Repeat, .Autoreverse],
                                   animations: {
                                    self.viewSmall.alpha = 0
            },
                                   completion: nil)

        UIView.animateWithDuration(0.5,
                                   delay: 0,
                                   options: [.Repeat, .Autoreverse],
                                   animations: {
                                    self.viewBig.alpha = 0
            },
                                   completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

这段代码不会在仅有的几个视图控制器上设置动画,并且视图控制器看起来是独立的,我猜没有与其他视图控制器的连接。因为此代码在连接到导航视图控制器的视图控制器上完美运行。

如何在独立视图控制器上制作它? 请帮忙。

找到了一个绝妙的解决方案。 使用 dispatch_after 捕捉持续时间和延迟。

func animate(){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {

        // Animate the transition
        UIView.animateWithDuration(0.5,
                               delay: 0,
                               options: [.Repeat, .Autoreverse],
                               animations: {
                                self.viewSmall.alpha = 0
        },
                               completion: nil)

        UIView.animateWithDuration(0.5,
                               delay: 0,
                               options: [.Repeat, .Autoreverse],
                               animations: {
                                self.viewBig.alpha = 0
        },
                               completion: nil)
    })
}

来源: Swift UIView animateWithDuration completion closure called immediately