Skip to content

Instantly share code, notes, and snippets.

@rafaelsachetto
Forked from kakopappa/swift
Last active September 18, 2019 20:20
Show Gist options
  • Save rafaelsachetto/6a719382f051048ccfceea7814ab9473 to your computer and use it in GitHub Desktop.
Save rafaelsachetto/6a719382f051048ccfceea7814ab9473 to your computer and use it in GitHub Desktop.
Show UIActivityIndicatorView inside UIImageView
//
// UIImageView+Extentions.swift
// MealSpecials
//
// Created by Aruna on 8/9/15.
// Copyright (c) 2015 com.mealspecials. All rights reserved.
//
import UIKit
import ObjectiveC
private var activityIndicatorAssociationKey: UInt8 = 0
private var imageStoredAssociationKey: UInt8 = 0
private var isLoadingAssociationKey: UInt8 = 0
extension UIImageView {
var activityIndicator: UIActivityIndicatorView {
get {
// swiftlint:disable:next line_length
if let activityIndicator = objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView {
return activityIndicator
}
let activityIndicator: UIActivityIndicatorView = .init(style: .gray)
activityIndicator.hidesWhenStopped = true
activityIndicator.center = .init(x: self.frame.size.width / 2,
y: self.frame.size.height / 2)
activityIndicator.autoresizingMask = [.flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleBottomMargin]
activityIndicator.isUserInteractionEnabled = false
imageStored = self.image
self.activityIndicator = activityIndicator
addSubview(self.activityIndicator)
return activityIndicator
}
set (newValue) {
objc_setAssociatedObject(self,
&activityIndicatorAssociationKey,
newValue,
.OBJC_ASSOCIATION_RETAIN)
}
}
private var imageStored: UIImage? {
get {
return objc_getAssociatedObject(self, &imageStoredAssociationKey) as? UIImage
}
set (newValue) {
objc_setAssociatedObject(self,
&imageStoredAssociationKey,
newValue,
.OBJC_ASSOCIATION_RETAIN)
}
}
var isLoading: Bool {
get {
return objc_getAssociatedObject(self, &isLoadingAssociationKey) as? Bool ?? false
}
set (newValue) {
newValue ? showActivityIndicator() : hideActivityIndicator()
objc_setAssociatedObject(self,
&isLoadingAssociationKey,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
private func showActivityIndicator() {
OperationQueue.main.addOperation { [weak self] () -> Void in
self?.activityIndicator.startAnimating()
self?.image = nil
}
}
private func hideActivityIndicator() {
OperationQueue.main.addOperation { [weak self] () -> Void in
self?.activityIndicator.stopAnimating()
self?.image = self?.imageStored
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment