Last active
January 5, 2023 18:33
-
-
Save DanBurkhardt/e9f083c9f849a351cf578f2002bb8446 to your computer and use it in GitHub Desktop.
Extension for UIViewController to show a loading indicator centered within the main view using frame animation built into UIImageView.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UIViewController+LoadingAnimation.swift | |
// | |
// Created by GigabiteLabs on 4/16/20 | |
// Swift Version: 5.0 | |
// | |
// Description: | |
// An extension for UIViewController using gif-like frame animation support | |
// in UIImageView to show a loading indicator centered within the main view. | |
// Note: | |
// This code assumes you have an imageset within your asset catalog | |
// where each image is numerically sequential (representing one frame each), | |
// and following the naming convention: "loading\(i)", where the initial image | |
// is named "loading0", and the last image is named "loading30". | |
import Foundation | |
extension UIViewController { | |
func presentLoadingAnimation() { | |
// Instantiate Image | |
let animatedView = UIImageView() | |
animatedView.frame.size = CGSize(width: 100, height: 100) | |
animatedView.center = view.center | |
animatedView.layer.cornerRadius = 13 | |
animatedView.backgroundColor = .clear | |
animatedView.tag = 99999 | |
animatedView.layer.zPosition = 0 | |
// Add GIF | |
var imageArray: [UIImage] = [] | |
for i in -1...30 { | |
if let image = UIImage(named: "loading\(i)"){ | |
imageArray.append(image) | |
} | |
} | |
animatedView.animationImages = imageArray | |
animatedView.animationDuration = 0.5 | |
animatedView.startAnimating() | |
//Add as Subview | |
view.addSubview(animatedView) | |
animatedView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true | |
animatedView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true | |
view.isUserInteractionEnabled = false | |
} | |
func hideLoadingAnimation() { | |
view.viewWithTag(99999)?.removeFromSuperview() | |
view.isUserInteractionEnabled = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment