无法在Swift中使用定时延迟为UIImage制作动画

时间:2018-02-13 13:43:55

标签: ios swift uiview uiimage

我试图在3秒钟后动画UIImage的alpha动画。默认情况下,alpha设置为0,3秒后,alpha应更改为1,从而将图像显示给用户。我为动画编写的代码确实将alpha设置为0,但是我无法在3秒后将alpha更改为1。我比较新,但不确定我在哪里出错了。这是我的代码。

import UIKit

class WelcomeOneViewController: UIViewController {

@IBOutlet weak var swipeImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    swipeImageView.alpha = 0
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    displaySwipeView()
}

func displaySwipeView() {
    UIView.animate(withDuration: 1.0, delay: 3.0, options: .beginFromCurrentState, animations: {

        DispatchQueue.main.async { [weak self] in
            self?.swipeImageView.alpha = 1
        }

    }, completion: nil)
}

}

2 个答案:

答案 0 :(得分:2)

尝试使用此代码:

import UIKit

class WelcomeOneViewController: UIViewController {

    @IBOutlet weak var swipeImageView: UIImageView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        swipeImageView.alpha = 0
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        displaySwipeView()
    }

    func displaySwipeView() {
        swipeImageView.alpha = 0
        UIView.animate(withDuration: 1.0, delay: 3.0, options: [], animations: {
            self.swipeImageView.alpha = 1
        }, completion: nil)
    }

}

答案 1 :(得分:1)

尝试在主队列上执行此操作:

func displaySwipeView() {
  UIView.animate(withDuration: 1.0, delay: 3.0, options: .beginFromCurrentState, animations: {

   DispatchQueue.main.async { [weak self] in
    self?.swipeImageView.alpha = 1
   }

  }, completion: nil)
}

希望它有所帮助!!