简体   繁体   中英

UIView.animateWithDuration doesn't animate on separate view controller

Setting animation to fade in and out repeatedly. 'viewSmall' and 'viewBig' are UIImageViews.

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.
    }
}

This code doesn't animate on a only few view controllers, and the view controllers seem independent, no segue to other view controllers, on my guess. Because this code works perfectly on view controllers connected to navigation view controller.

How can I make it on independent view controller? Please help.

Found a brilliant solution. Used dispatch_after to catch duration and delay.

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)
    })
}

Source from: Swift UIView animateWithDuration completion closure called immediately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM