-
Notifications
You must be signed in to change notification settings - Fork 82
/
EZLoadingActivity.swift
executable file
·335 lines (295 loc) · 12.8 KB
/
EZLoadingActivity.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//
// EZLoadingActivity.swift
// EZLoadingActivity
//
// Created by Goktug Yilmaz on 02/06/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
public struct EZLoadingActivity {
//==========================================================================================================
// Feel free to edit these variables
//==========================================================================================================
public struct Settings {
public static var BackgroundColor = UIColor(red: 31/255, green: 38/255, blue: 5/255, alpha: 0.5)
public static var ActivityColor = UIColor(red: 141/255, green: 141/255, blue: 6/255, alpha: 1.0)
public static var TextColor = UIColor(red: 250/255, green: 250/255, blue: 17/255, alpha: 1.0)
public static var FontName = "Cochin-BoldItalic"
// Other possible stuff: ✓ ✓ ✔︎ ✕ ✖︎ ✘
public static var SuccessIcon = "✔︎"
public static var FailIcon = "✘"
public static var SuccessText = "Success"
public static var FailText = "Failure"
public static var SuccessColor = UIColor(red: 68/255, green: 118/255, blue: 4/255, alpha: 1.0)
public static var FailColor = UIColor(red: 255/255, green: 75/255, blue: 56/255, alpha: 1.0)
public static var ActivityWidth = UIScreen.ScreenWidth / Settings.WidthDivision
public static var ActivityHeight = ActivityWidth / 3
public static var ShadowEnabled = true
public static var WidthDivision: CGFloat {
get {
if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
return 3.5
} else {
return 1.6
}
}
}
public static var LoadOverApplicationWindow = false
public static var DarkensBackground = false
}
fileprivate static var instance: LoadingActivity?
fileprivate static var hidingInProgress = false
fileprivate static var overlay: UIView!
/// Disable UI stops users touch actions until EZLoadingActivity is hidden. Return success status
@discardableResult
public static func show(_ text: String, disableUI: Bool) -> Bool {
guard instance == nil else {
print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one")
return false
}
guard topMostController != nil else {
print("EZLoadingActivity Error: You don't have any views set. You may be calling them in viewDidLoad. Try viewDidAppear instead.")
return false
}
// Separate creation from showing
instance = LoadingActivity(text: text, disableUI: disableUI)
DispatchQueue.main.async {
if Settings.DarkensBackground {
if overlay == nil {
overlay = UIView(frame: UIApplication.shared.keyWindow!.frame)
}
overlay.backgroundColor = UIColor.black.withAlphaComponent(0)
topMostController?.view.addSubview(overlay)
UIView.animate(withDuration: 0.2, animations: {overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0.5)})
}
instance?.showLoadingActivity()
}
return true
}
@discardableResult
public static func showWithDelay(_ text: String, disableUI: Bool, seconds: Double) -> Bool {
let showValue = show(text, disableUI: disableUI)
delay(seconds) { () -> () in
_ = hide(true, animated: false)
}
return showValue
}
public static func showOnController(_ text: String, disableUI: Bool, controller:UIViewController) -> Bool{
guard instance == nil else {
print("EZLoadingActivity: You still have an active activity, please stop that before creating a new one")
return false
}
instance = LoadingActivity(text: text, disableUI: disableUI)
DispatchQueue.main.async {
instance?.showLoadingWithController(controller)
}
return true
}
/// Returns success status
@discardableResult
public static func hide(_ success: Bool? = nil, animated: Bool = false) -> Bool {
guard instance != nil else {
print("EZLoadingActivity: You don't have an activity instance")
return false
}
guard hidingInProgress == false else {
print("EZLoadingActivity: Hiding already in progress")
return false
}
if !Thread.current.isMainThread {
DispatchQueue.main.async {
instance?.hideLoadingActivity(success, animated: animated)
}
} else {
instance?.hideLoadingActivity(success, animated: animated)
}
if overlay != nil {
UIView.animate(withDuration: 0.2, animations: {
overlay.backgroundColor = overlay.backgroundColor?.withAlphaComponent(0)
}, completion: { _ in
overlay.removeFromSuperview()
})
}
return true
}
fileprivate static func delay(_ seconds: Double, after: @escaping ()->()) {
let queue = DispatchQueue.main
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
fileprivate class LoadingActivity: UIView {
var textLabel: UILabel!
var activityView: UIActivityIndicatorView!
var icon: UILabel!
var UIDisabled = false
convenience init(text: String, disableUI: Bool) {
self.init(frame: CGRect(x: 0, y: 0, width: Settings.ActivityWidth, height: Settings.ActivityHeight))
center = CGPoint(x: topMostController!.view.bounds.midX, y: topMostController!.view.bounds.midY)
autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
backgroundColor = Settings.BackgroundColor
alpha = 1
layer.cornerRadius = 8
if Settings.ShadowEnabled {
createShadow()
}
let yPosition = frame.height/2 - 20
activityView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
activityView.frame = CGRect(x: 10, y: yPosition, width: 40, height: 40)
activityView.color = Settings.ActivityColor
activityView.startAnimating()
textLabel = UILabel(frame: CGRect(x: 60, y: yPosition, width: Settings.ActivityWidth - 70, height: 40))
textLabel.textColor = Settings.TextColor
textLabel.font = UIFont(name: Settings.FontName, size: 30)
textLabel.adjustsFontSizeToFitWidth = true
textLabel.minimumScaleFactor = 0.25
textLabel.textAlignment = NSTextAlignment.center
textLabel.text = text
if disableUI {
UIApplication.shared.beginIgnoringInteractionEvents()
UIDisabled = true
}
}
func showLoadingActivity() {
addSubview(activityView)
addSubview(textLabel)
//make it smoothly
self.alpha = 0
if Settings.LoadOverApplicationWindow {
UIApplication.shared.windows.first?.addSubview(self)
} else {
topMostController!.view.addSubview(self)
}
//make it smoothly
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1
})
}
func showLoadingWithController(_ controller:UIViewController){
addSubview(activityView)
addSubview(textLabel)
//make it smoothly
self.alpha = 0
controller.view.addSubview(self)
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 1
})
}
func createShadow() {
layer.shadowPath = createShadowPath().cgPath
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 5
layer.shadowOpacity = 0.5
}
func createShadowPath() -> UIBezierPath {
let myBezier = UIBezierPath()
myBezier.move(to: CGPoint(x: -3, y: -3))
myBezier.addLine(to: CGPoint(x: frame.width + 3, y: -3))
myBezier.addLine(to: CGPoint(x: frame.width + 3, y: frame.height + 3))
myBezier.addLine(to: CGPoint(x: -3, y: frame.height + 3))
myBezier.close()
return myBezier
}
func hideLoadingActivity(_ success: Bool?, animated: Bool) {
hidingInProgress = true
if UIDisabled {
UIApplication.shared.endIgnoringInteractionEvents()
}
var animationDuration: Double = 0
if success != nil {
if success! {
animationDuration = 0.5
} else {
animationDuration = 1
}
}
icon = UILabel(frame: CGRect(x: 10, y: frame.height/2 - 20, width: 40, height: 40))
icon.font = UIFont(name: Settings.FontName, size: 60)
icon.textAlignment = NSTextAlignment.center
if animated {
textLabel.fadeTransition(animationDuration)
}
if success != nil {
if success! {
icon.textColor = Settings.SuccessColor
icon.text = Settings.SuccessIcon
textLabel.text = Settings.SuccessText
} else {
icon.textColor = Settings.FailColor
icon.text = Settings.FailIcon
textLabel.text = Settings.FailText
}
}
addSubview(icon)
if animated {
icon.alpha = 0
activityView.stopAnimating()
UIView.animate(withDuration: animationDuration, animations: {
self.icon.alpha = 1
}, completion: { (value: Bool) in
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 0
}, completion: { (success) in
self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration)
})
instance = nil
hidingInProgress = false
})
} else {
activityView.stopAnimating()
self.callSelectorAsync(#selector(UIView.removeFromSuperview), delay: animationDuration)
instance = nil
hidingInProgress = false
}
}
}
}
private extension UIView {
/// Extension: insert view.fadeTransition right before changing content
func fadeTransition(_ duration: CFTimeInterval) {
let animation: CATransition = CATransition()
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
self.layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
private extension NSObject {
func callSelectorAsync(_ selector: Selector, delay: TimeInterval) {
let timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: selector, userInfo: nil, repeats: false)
RunLoop.main.add(timer, forMode: RunLoop.Mode.common)
}
}
private extension UIScreen {
class var Orientation: UIInterfaceOrientation {
get {
return UIApplication.shared.statusBarOrientation
}
}
class var ScreenWidth: CGFloat {
get {
if Orientation.isPortrait {
return UIScreen.main.bounds.size.width
} else {
return UIScreen.main.bounds.size.height
}
}
}
class var ScreenHeight: CGFloat {
get {
if Orientation.isPortrait {
return UIScreen.main.bounds.size.height
} else {
return UIScreen.main.bounds.size.width
}
}
}
}
private var topMostController: UIViewController? {
var presentedVC = UIApplication.shared.keyWindow?.rootViewController
while let pVC = presentedVC?.presentedViewController {
presentedVC = pVC
}
return presentedVC
}