LoginSignup
0
0

More than 1 year has passed since last update.

Lottieアニメーションをすぐ使えるように

Posted at

今回の内容

E0FF5A40-FB6C-487E-A213-E51CF49AC396_4_5005_c.jpeg

  • 半透明なViewの上にLottieをアニメーションさせます。

コードと簡単解説

  • 今回はUIButtonextensionしてます。
  • showContent:Stringでアニメーションさせるデータを指定
  • animationTime:Doubleでアニメーションさせる時間を指定
extension UIButton{

    func showAnimation(showContent:String?,animationTime:Double?,targetView:UIView,completion: @escaping (Bool) -> Void){

        guard let content = showContent else { completion(false); return }
        guard let time = animationTime else { completion(false); return }

        let underView = UIView(frame: CGRect(x: targetView.frame.maxX / 4, y: targetView.frame.maxY * 0.25, width: targetView.frame.width / 2, height: targetView.frame.width / 2))
        underView.layer.cornerRadius = 15.0
        underView.backgroundColor = .darkGray
        underView.alpha = 0.7
        targetView.addSubview(underView)

        let animationView = AnimationView()
        animationView.frame = CGRect(x: targetView.frame.maxX / 4, y: targetView.frame.maxY * 0.25, width: targetView.frame.width / 2, height: targetView.frame.width / 2)
        animationView.layer.cornerRadius = 15.0
        animationView.backgroundColor = .clear
        animationView.animation = Animation.named(content)
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        animationView.play(completion: nil)
        targetView.addSubview(animationView)

        DispatchQueue.main.asyncAfter(deadline: .now() + time) {

            completion(true)
            animationView.stop()
            animationView.removeFromSuperview()
            underView.removeFromSuperview()
        }
    }

}

実際に使用

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRect(x: view.frame.maxX / 4, y: view.frame.maxY * 0.7, width: view.frame.width / 2, height: view.frame.height / 15))
        button.backgroundColor = .systemTeal
        button.setTitle("ShowAnimation", for: .normal)
        button.titleLabel?.textColor = .white
        button.addTarget(self, action: #selector(showAnimation), for: .touchDown)
        view.addSubview(button)
    }

    @objc func showAnimation(button:UIButton){

        button.showAnimation(showContent: "5", animationTime: 10, targetView: self.view) { result in

            if result == false{

                return
            }

            print("終わり")
        }
    }

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0