-
Notifications
You must be signed in to change notification settings - Fork 753
Expand file tree
/
Copy pathSCLAlertView.swift
More file actions
1404 lines (1196 loc) · 66.1 KB
/
SCLAlertView.swift
File metadata and controls
1404 lines (1196 loc) · 66.1 KB
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// SCLAlertView.swift
// SCLAlertView Example
//
// Created by Viktor Radchenko on 6/5/14.
// Copyright (c) 2014 Viktor Radchenko. All rights reserved.
//
import Foundation
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
// Pop Up Styles
public enum SCLAlertViewStyle {
case success, error, notice, warning, info, edit, wait, question, none
public var defaultColorInt: UInt {
switch self {
case .success:
return 0x22B573
case .error:
return 0xC1272D
case .notice:
return 0x727375
case .warning:
return 0xFFD110
case .info:
return 0x2866BF
case .edit:
return 0xA429FF
case .wait:
return 0xD62DA5
case .question:
return 0x727375
case .none:
return 0x000000
}
}
}
// Animation Styles
public enum SCLAnimationStyle {
case noAnimation, topToBottom, bottomToTop, leftToRight, rightToLeft
}
// Action Types
public enum SCLActionType {
case none, selector, closure
}
public enum SCLAlertButtonLayout {
case horizontal, vertical
}
// Button sub-class
open class SCLButton: UIButton {
var actionType = SCLActionType.none
var target:AnyObject!
var selector:Selector!
var action:(()->Void)!
var customBackgroundColor:UIColor?
var customTextColor:UIColor?
var initialTitle:String!
var showTimeout:ShowTimeoutConfiguration?
public struct ShowTimeoutConfiguration {
let prefix: String
let suffix: String
public init(prefix: String = "", suffix: String = "") {
self.prefix = prefix
self.suffix = suffix
}
}
public init() {
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override public init(frame:CGRect) {
super.init(frame:frame)
}
}
// Allow alerts to be closed/renamed in a chainable manner
// Example: SCLAlertView().showSuccess(self, title: "Test", subTitle: "Value").close()
open class SCLAlertViewResponder {
let alertview: SCLAlertView
// Initialisation and Title/Subtitle/Close functions
public init(alertview: SCLAlertView) {
self.alertview = alertview
}
open func setTitle(_ title: String) {
self.alertview.labelTitle.text = title
}
open func setSubTitle(_ subTitle: String?) {
self.alertview.viewText.text = subTitle != nil ? subTitle : ""
}
open func close() {
self.alertview.hideView()
}
open func setDismissBlock(_ dismissBlock: @escaping DismissBlock) {
self.alertview.dismissBlock = dismissBlock
}
}
let kCircleHeightBackground: CGFloat = 62.0
let uniqueTag: Int = Int(arc4random() % UInt32(Int32.max))
let uniqueAccessibilityIdentifier: String = "SCLAlertView"
public typealias DismissBlock = () -> Void
// The Main Class
open class SCLAlertView: UIViewController {
public struct SCLAppearance {
let kDefaultShadowOpacity: CGFloat
let kCircleTopPosition: CGFloat
let kCircleBackgroundTopPosition: CGFloat
let kCircleHeight: CGFloat
let kCircleIconHeight: CGFloat
let kTitleHeight:CGFloat
let kTitleMinimumScaleFactor: CGFloat
let kWindowWidth: CGFloat
var kWindowHeight: CGFloat
var kTextHeight: CGFloat
let kTextFieldHeight: CGFloat
let kTextViewdHeight: CGFloat
let kButtonHeight: CGFloat
let circleBackgroundColor: UIColor
let contentViewColor: UIColor
let contentViewBorderColor: UIColor
let titleColor: UIColor
let subTitleColor: UIColor
let margin: Margin
/// Margin for SCLAlertView.
public struct Margin {
//vertical
/// The spacing between title's top and window's top.
public var titleTop: CGFloat
/// The spacing between textView/customView's bottom and first button's top.
public var textViewBottom: CGFloat
/// The spacing between buttons.
public var buttonSpacing: CGFloat
/// The spacing between textField.
public var textFieldSpacing: CGFloat
/// The last button's bottom margin against alertView's bottom
public var bottom: CGFloat
//Horizontal
/// The subView's horizontal margin.
public var horizontal: CGFloat = 12
public init(titleTop: CGFloat = 30,
textViewBottom: CGFloat = 12,
buttonSpacing: CGFloat = 10,
textFieldSpacing: CGFloat = 15,
bottom: CGFloat = 14,
horizontal: CGFloat = 12) {
self.titleTop = titleTop
self.textViewBottom = textViewBottom
self.buttonSpacing = buttonSpacing
self.textFieldSpacing = textFieldSpacing
self.bottom = bottom
self.horizontal = horizontal
}
}
// Fonts
let kTitleFont: UIFont
let kTextFont: UIFont
let kButtonFont: UIFont
// UI Options
var disableTapGesture: Bool
var showCloseButton: Bool
var showCircularIcon: Bool
var shouldAutoDismiss: Bool // Set this false to 'Disable' Auto hideView when SCLButton is tapped
var contentViewCornerRadius : CGFloat
var fieldCornerRadius : CGFloat
var buttonCornerRadius : CGFloat
var dynamicAnimatorActive : Bool
var buttonsLayout: SCLAlertButtonLayout
var textViewAlignment: NSTextAlignment = .center
// Actions
var hideWhenBackgroundViewIsTapped: Bool
// Activity indicator
var activityIndicatorStyle: UIActivityIndicatorView.Style
public init(kDefaultShadowOpacity: CGFloat = 0.7, kCircleTopPosition: CGFloat = 0.0, kCircleBackgroundTopPosition: CGFloat = 6.0, kCircleHeight: CGFloat = 56.0, kCircleIconHeight: CGFloat = 20.0, kTitleHeight:CGFloat = 25.0, kWindowWidth: CGFloat = 240.0, kWindowHeight: CGFloat = 178.0, kTextHeight: CGFloat = 90.0, kTextFieldHeight: CGFloat = 30.0, kTextViewdHeight: CGFloat = 80.0, kButtonHeight: CGFloat = 35.0, kTitleFont: UIFont = UIFont.systemFont(ofSize: 20), kTitleMinimumScaleFactor: CGFloat = 1.0, kTextFont: UIFont = UIFont.systemFont(ofSize: 14), kButtonFont: UIFont = UIFont.boldSystemFont(ofSize: 14), showCloseButton: Bool = true, showCircularIcon: Bool = true, shouldAutoDismiss: Bool = true, contentViewCornerRadius: CGFloat = 5.0, fieldCornerRadius: CGFloat = 3.0, buttonCornerRadius: CGFloat = 3.0, hideWhenBackgroundViewIsTapped: Bool = false, circleBackgroundColor: UIColor = UIColor.white, contentViewColor: UIColor = UIColorFromRGB(0xFFFFFF), contentViewBorderColor: UIColor = UIColorFromRGB(0xCCCCCC), titleColor: UIColor = UIColorFromRGB(0x4D4D4D), subTitleColor: UIColor = UIColorFromRGB(0x4D4D4D), margin: Margin = Margin(), dynamicAnimatorActive: Bool = false, disableTapGesture: Bool = false, buttonsLayout: SCLAlertButtonLayout = .vertical, activityIndicatorStyle: UIActivityIndicatorView.Style = .white, textViewAlignment: NSTextAlignment = .center) {
self.kDefaultShadowOpacity = kDefaultShadowOpacity
self.kCircleTopPosition = kCircleTopPosition
self.kCircleBackgroundTopPosition = kCircleBackgroundTopPosition
self.kCircleHeight = kCircleHeight
self.kCircleIconHeight = kCircleIconHeight
self.kTitleHeight = kTitleHeight
self.kWindowWidth = kWindowWidth
self.kWindowHeight = kWindowHeight
self.kTextHeight = kTextHeight
self.kTextFieldHeight = kTextFieldHeight
self.kTextViewdHeight = kTextViewdHeight
self.kButtonHeight = kButtonHeight
self.circleBackgroundColor = circleBackgroundColor
self.contentViewColor = contentViewColor
self.contentViewBorderColor = contentViewBorderColor
self.titleColor = titleColor
self.subTitleColor = subTitleColor
self.margin = margin
self.kTitleFont = kTitleFont
self.kTitleMinimumScaleFactor = kTitleMinimumScaleFactor
self.kTextFont = kTextFont
self.kButtonFont = kButtonFont
self.disableTapGesture = disableTapGesture
self.showCloseButton = showCloseButton
self.showCircularIcon = showCircularIcon
self.shouldAutoDismiss = shouldAutoDismiss
self.contentViewCornerRadius = contentViewCornerRadius
self.fieldCornerRadius = fieldCornerRadius
self.buttonCornerRadius = buttonCornerRadius
self.hideWhenBackgroundViewIsTapped = hideWhenBackgroundViewIsTapped
self.dynamicAnimatorActive = dynamicAnimatorActive
self.buttonsLayout = buttonsLayout
self.activityIndicatorStyle = activityIndicatorStyle
self.textViewAlignment = textViewAlignment
}
mutating func setkWindowHeight(_ kWindowHeight:CGFloat) {
self.kWindowHeight = kWindowHeight
}
mutating func setkTextHeight(_ kTextHeight:CGFloat) {
self.kTextHeight = kTextHeight
}
}
public struct SCLTimeoutConfiguration {
public typealias ActionType = () -> Void
var value: TimeInterval
let action: ActionType
mutating func increaseValue(by: Double) {
self.value = value + by
}
public init(timeoutValue: TimeInterval, timeoutAction: @escaping ActionType) {
self.value = timeoutValue
self.action = timeoutAction
}
}
var appearance: SCLAppearance!
// UI Colour
var viewColor = UIColor()
// UI Options
open var iconTintColor: UIColor?
open var customSubview : UIView?
// Members declaration
var baseView = UIView()
var labelTitle = UILabel()
var viewText = UITextView()
var contentView = UIView()
var circleBG = UIView(frame:CGRect(x:0, y:0, width:kCircleHeightBackground, height:kCircleHeightBackground))
var circleView = UIView()
var circleIconView : UIView?
var timeout: SCLTimeoutConfiguration?
var showTimeoutTimer: Timer?
var timeoutTimer: Timer?
var dismissBlock : DismissBlock?
fileprivate var inputs = [UITextField]()
fileprivate var input = [UITextView]()
internal var buttons = [SCLButton]()
fileprivate var selfReference: SCLAlertView?
public init(appearance: SCLAppearance) {
self.appearance = appearance
super.init(nibName:nil, bundle:nil)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
required public init() {
appearance = SCLAppearance()
super.init(nibName:nil, bundle:nil)
setup()
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
if appearance == nil {
appearance = SCLAppearance()
}
super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil)
}
fileprivate func setup() {
// Set up main view
view.frame = UIScreen.main.bounds
view.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth]
view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:appearance.kDefaultShadowOpacity)
view.addSubview(baseView)
// Base View
baseView.frame = view.frame
baseView.addSubview(contentView)
// Content View
contentView.layer.cornerRadius = appearance.contentViewCornerRadius
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
contentView.addSubview(labelTitle)
contentView.addSubview(viewText)
// Circle View
circleBG.backgroundColor = appearance.circleBackgroundColor
circleBG.layer.cornerRadius = circleBG.frame.size.height / 2
baseView.addSubview(circleBG)
circleBG.addSubview(circleView)
let x = (kCircleHeightBackground - appearance.kCircleHeight) / 2
circleView.frame = CGRect(x:x, y:x+appearance.kCircleTopPosition, width:appearance.kCircleHeight, height:appearance.kCircleHeight)
circleView.layer.cornerRadius = circleView.frame.size.height / 2
// Title
labelTitle.numberOfLines = 0
labelTitle.textAlignment = .center
labelTitle.font = appearance.kTitleFont
if(appearance.kTitleMinimumScaleFactor < 1){
labelTitle.minimumScaleFactor = appearance.kTitleMinimumScaleFactor
labelTitle.adjustsFontSizeToFitWidth = true
}
labelTitle.frame = CGRect(x:appearance.margin.horizontal, y:appearance.margin.titleTop, width: subViewsWidth, height:appearance.kTitleHeight)
// View text
viewText.isEditable = false
viewText.isSelectable = false
viewText.textAlignment = appearance.textViewAlignment
viewText.textContainerInset = UIEdgeInsets.zero
viewText.textContainer.lineFragmentPadding = 0;
viewText.font = appearance.kTextFont
// Colours
contentView.backgroundColor = appearance.contentViewColor
viewText.backgroundColor = appearance.contentViewColor
labelTitle.textColor = appearance.titleColor
viewText.textColor = appearance.subTitleColor
contentView.layer.borderColor = appearance.contentViewBorderColor.cgColor
//Gesture Recognizer for tapping outside the textinput
if appearance.disableTapGesture == false {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SCLAlertView.tapped(_:)))
tapGesture.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tapGesture)
}
view.isAccessibilityElement = true
view.accessibilityLabel = "alert"
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard !keyboardHasBeenShown else {
return
}
let rv = UIApplication.shared.keyWindow! as UIWindow
let sz = rv.frame.size
// Set background frame
view.frame.size = sz
let defaultTopOffset: CGFloat = 32
// get actual height of title text
var titleActualHeight: CGFloat = 0
if let title = labelTitle.text {
titleActualHeight = title.heightWithConstrainedWidth(width: subViewsWidth, font: labelTitle.font) + 10
// get the larger height for the title text
titleActualHeight = (titleActualHeight > appearance.kTitleHeight ? titleActualHeight : appearance.kTitleHeight)
}
// computing the right size to use for the textView
let maxHeight = sz.height - 100 // max overall height
var consumedHeight = CGFloat(0)
consumedHeight += (titleActualHeight > 0 ? appearance.margin.titleTop + titleActualHeight : defaultTopOffset)
consumedHeight += appearance.margin.bottom
let buttonMargin = appearance.margin.buttonSpacing
let textFieldMargin = appearance.margin.textFieldSpacing
if appearance.buttonsLayout == .vertical {
consumedHeight += appearance.kButtonHeight * CGFloat(buttons.count)
consumedHeight += buttonMargin * (CGFloat(buttons.count) - 1)
} else {
consumedHeight += appearance.kButtonHeight
}
consumedHeight += (appearance.kTextFieldHeight + textFieldMargin) * CGFloat(inputs.count)
consumedHeight += appearance.kTextViewdHeight * CGFloat(input.count)
let maxViewTextHeight = maxHeight - consumedHeight
let viewTextWidth = subViewsWidth
var viewTextHeight = appearance.kTextHeight
// Check if there is a custom subview and add it over the textview
if let customSubview = customSubview {
viewTextHeight = min(customSubview.frame.height, maxViewTextHeight)
viewText.text = ""
viewText.addSubview(customSubview)
} else if viewText.text.isEmpty {
viewTextHeight = 0
} else {
// computing the right size to use for the textView
let suggestedViewTextSize = viewText.sizeThatFits(CGSize(width: viewTextWidth, height: CGFloat.greatestFiniteMagnitude))
viewTextHeight = min(suggestedViewTextSize.height, maxViewTextHeight)
// scroll management
if (suggestedViewTextSize.height > maxViewTextHeight) {
viewText.isScrollEnabled = true
} else {
viewText.isScrollEnabled = false
}
}
var windowHeight = consumedHeight + viewTextHeight
windowHeight += viewText.text.isEmpty ? 0 : appearance.margin.textViewBottom // only viewText.text is not empty should have margin.
// Set frames
var x = (sz.width - appearance.kWindowWidth) / 2
var y = (sz.height - windowHeight - (appearance.kCircleHeight / 8)) / 2
contentView.frame = CGRect(x:x, y:y, width:appearance.kWindowWidth, height:windowHeight)
contentView.layer.cornerRadius = appearance.contentViewCornerRadius
y -= kCircleHeightBackground * 0.6
x = (sz.width - kCircleHeightBackground) / 2
circleBG.frame = CGRect(x:x, y:y+appearance.kCircleBackgroundTopPosition, width:kCircleHeightBackground, height:kCircleHeightBackground)
//adjust Title frame based on circularIcon show/hide flag
// let titleOffset : CGFloat = appearance.showCircularIcon ? 0.0 : -12.0
let titleOffset: CGFloat = 0
labelTitle.frame = labelTitle.frame.offsetBy(dx: 0, dy: titleOffset)
// Subtitle
y = titleActualHeight > 0 ? appearance.margin.titleTop + titleActualHeight + titleOffset : defaultTopOffset
viewText.frame = CGRect(x:appearance.margin.horizontal, y:y, width: viewTextWidth, height:viewTextHeight)
// Text fields
y += viewTextHeight
y += viewText.text.isEmpty ? 0 : appearance.margin.textViewBottom // only viewText.text is not empty should have margin.
for txt in inputs {
txt.frame = CGRect(x:appearance.margin.horizontal, y:y, width:subViewsWidth, height:appearance.kTextFieldHeight)
txt.layer.cornerRadius = appearance.fieldCornerRadius
y += appearance.kTextFieldHeight + textFieldMargin
}
for txt in input {
txt.frame = CGRect(x:appearance.margin.horizontal, y:y, width:subViewsWidth, height:appearance.kTextViewdHeight - appearance.margin.textViewBottom)
//txt.layer.cornerRadius = fieldCornerRadius
y += appearance.kTextViewdHeight
}
// Buttons
var buttonX = appearance.margin.horizontal
switch appearance.buttonsLayout {
case .vertical:
for btn in buttons {
btn.frame = CGRect(x:buttonX, y:y, width:subViewsWidth, height:appearance.kButtonHeight)
btn.layer.cornerRadius = appearance.buttonCornerRadius
y += appearance.kButtonHeight + buttonMargin
}
case .horizontal:
let numberOfButton = CGFloat(buttons.count)
let buttonsSpace = numberOfButton >= 1 ? CGFloat(10) * (numberOfButton - 1) : 0
let widthEachButton = (subViewsWidth - buttonsSpace) / numberOfButton
for btn in buttons {
btn.frame = CGRect(x:buttonX, y:y, width: widthEachButton, height:appearance.kButtonHeight)
btn.layer.cornerRadius = appearance.buttonCornerRadius
buttonX += widthEachButton
buttonX += buttonsSpace
}
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(SCLAlertView.keyboardWillShow(_:)), name:UIResponder.keyboardWillShowNotification, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(SCLAlertView.keyboardWillHide(_:)), name:UIResponder.keyboardWillHideNotification, object: nil);
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
override open func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?) {
if event?.touches(for: view)?.count > 0 {
view.endEditing(true)
}
}
open func addTextField(_ title:String?=nil)->UITextField {
// Update view height
appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextFieldHeight)
// Add text field
let txt = UITextField()
txt.borderStyle = UITextField.BorderStyle.roundedRect
txt.font = appearance.kTextFont
txt.autocapitalizationType = UITextAutocapitalizationType.words
txt.clearButtonMode = UITextField.ViewMode.whileEditing
txt.layer.masksToBounds = true
txt.layer.borderWidth = 1.0
if title != nil {
txt.placeholder = title!
}
contentView.addSubview(txt)
inputs.append(txt)
return txt
}
open func addTextView()->UITextView {
// Update view height
appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kTextViewdHeight)
// Add text view
let txt = UITextView()
// No placeholder with UITextView but you can use KMPlaceholderTextView library
txt.font = appearance.kTextFont
//txt.autocapitalizationType = UITextAutocapitalizationType.Words
//txt.clearButtonMode = UITextFieldViewMode.WhileEditing
txt.layer.masksToBounds = true
txt.layer.borderWidth = 1.0
contentView.addSubview(txt)
input.append(txt)
return txt
}
@discardableResult
open func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showTimeout:SCLButton.ShowTimeoutConfiguration? = nil, action:@escaping ()->Void)->SCLButton {
let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor, showTimeout: showTimeout)
btn.actionType = SCLActionType.closure
btn.action = action
btn.addTarget(self, action:#selector(SCLAlertView.buttonTapped(_:)), for:.touchUpInside)
btn.addTarget(self, action:#selector(SCLAlertView.buttonTapDown(_:)), for:[.touchDown, .touchDragEnter])
btn.addTarget(self, action:#selector(SCLAlertView.buttonRelease(_:)), for:[.touchUpInside, .touchUpOutside, .touchCancel, .touchDragOutside] )
return btn
}
@discardableResult
open func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showTimeout:SCLButton.ShowTimeoutConfiguration? = nil, target:AnyObject, selector:Selector)->SCLButton {
let btn = addButton(title, backgroundColor: backgroundColor, textColor: textColor, showTimeout: showTimeout)
btn.actionType = SCLActionType.selector
btn.target = target
btn.selector = selector
btn.addTarget(self, action:#selector(SCLAlertView.buttonTapped(_:)), for:.touchUpInside)
btn.addTarget(self, action:#selector(SCLAlertView.buttonTapDown(_:)), for:[.touchDown, .touchDragEnter])
btn.addTarget(self, action:#selector(SCLAlertView.buttonRelease(_:)), for:[.touchUpInside, .touchUpOutside, .touchCancel, .touchDragOutside] )
return btn
}
@discardableResult
fileprivate func addButton(_ title:String, backgroundColor:UIColor? = nil, textColor:UIColor? = nil, showTimeout:SCLButton.ShowTimeoutConfiguration? = nil)->SCLButton {
// Update view height
appearance.setkWindowHeight(appearance.kWindowHeight + appearance.kButtonHeight)
// Add button
let btn = SCLButton()
btn.layer.masksToBounds = true
btn.setTitle(title, for: .normal)
btn.titleLabel?.font = appearance.kButtonFont
btn.customBackgroundColor = backgroundColor
btn.customTextColor = textColor
btn.initialTitle = title
btn.showTimeout = showTimeout
contentView.addSubview(btn)
buttons.append(btn)
return btn
}
@objc func buttonTapped(_ btn:SCLButton) {
let localAccessibilityValue = "\(btn.title(for: .normal) ?? "The") button tapped"
self.accessibilityValue = localAccessibilityValue
UIAccessibility.post(notification: .announcement, argument: localAccessibilityValue)
if btn.actionType == SCLActionType.closure {
btn.action()
} else if btn.actionType == SCLActionType.selector {
let ctrl = UIControl()
ctrl.sendAction(btn.selector, to:btn.target, for:nil)
} else {
print("Unknow action type for button")
}
if(self.view.alpha != 0.0 && appearance.shouldAutoDismiss){ hideView() }
}
@objc func buttonTapDown(_ btn:SCLButton) {
var hue : CGFloat = 0
var saturation : CGFloat = 0
var brightness : CGFloat = 0
var alpha : CGFloat = 0
let pressBrightnessFactor = 0.85
btn.backgroundColor?.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
brightness = brightness * CGFloat(pressBrightnessFactor)
btn.backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
@objc func buttonRelease(_ btn:SCLButton) {
btn.backgroundColor = btn.customBackgroundColor ?? viewColor
}
var tmpContentViewFrameOrigin: CGPoint?
var tmpCircleViewFrameOrigin: CGPoint?
var keyboardHasBeenShown:Bool = false
@objc func keyboardWillShow(_ notification: Notification) {
keyboardHasBeenShown = true
guard let userInfo = (notification as NSNotification).userInfo else {return}
guard let endKeyBoardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.minY else {return}
if tmpContentViewFrameOrigin == nil {
tmpContentViewFrameOrigin = self.contentView.frame.origin
}
if tmpCircleViewFrameOrigin == nil {
tmpCircleViewFrameOrigin = self.circleBG.frame.origin
}
var newContentViewFrameY = self.contentView.frame.maxY - endKeyBoardFrame
if newContentViewFrameY < 0 {
newContentViewFrameY = 0
}
let newBallViewFrameY = self.circleBG.frame.origin.y - newContentViewFrameY
self.contentView.frame.origin.y -= newContentViewFrameY
self.circleBG.frame.origin.y = newBallViewFrameY
}
@objc func keyboardWillHide(_ notification: Notification) {
if(keyboardHasBeenShown){//This could happen on the simulator (keyboard will be hidden)
if(self.tmpContentViewFrameOrigin != nil){
self.contentView.frame.origin.y = self.tmpContentViewFrameOrigin!.y
self.tmpContentViewFrameOrigin = nil
}
if(self.tmpCircleViewFrameOrigin != nil){
self.circleBG.frame.origin.y = self.tmpCircleViewFrameOrigin!.y
self.tmpCircleViewFrameOrigin = nil
}
keyboardHasBeenShown = false
}
}
//Dismiss keyboard when tapped outside textfield & close SCLAlertView when hideWhenBackgroundViewIsTapped
@objc func tapped(_ gestureRecognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
if let tappedView = gestureRecognizer.view , tappedView.hitTest(gestureRecognizer.location(in: tappedView), with: nil) == baseView && appearance.hideWhenBackgroundViewIsTapped {
hideView()
}
}
// showCustom(view, title, subTitle, UIColor, UIImage)
@discardableResult
open func showCustom(_ title: String, subTitle: String? = nil, color: UIColor, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
var colorAsUInt32 : UInt32 = 0
colorAsUInt32 += UInt32(red * 255.0) << 16
colorAsUInt32 += UInt32(green * 255.0) << 8
colorAsUInt32 += UInt32(blue * 255.0)
let colorAsUInt = UInt(colorAsUInt32)
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .success, colorStyle: colorAsUInt, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showSuccess(view, title, subTitle)
@discardableResult
open func showSuccess(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.success.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .success, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showError(view, title, subTitle)
@discardableResult
open func showError(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.error.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .error, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showNotice(view, title, subTitle)
@discardableResult
open func showNotice(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.notice.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .notice, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showWarning(view, title, subTitle)
@discardableResult
open func showWarning(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.warning.defaultColorInt, colorTextButton: UInt=0x000000, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .warning, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showInfo(view, title, subTitle)
@discardableResult
open func showInfo(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.info.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .info, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showWait(view, title, subTitle)
@discardableResult
open func showWait(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt?=SCLAlertViewStyle.wait.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .wait, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
@discardableResult
open func showEdit(_ title: String, subTitle: String? = nil, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt=SCLAlertViewStyle.edit.defaultColorInt, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout: timeout, completeText:closeButtonTitle, style: .edit, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showTitle(view, title, subTitle, style)
@discardableResult
open func showTitle(_ title: String, subTitle: String? = nil, style: SCLAlertViewStyle, closeButtonTitle:String?=nil, timeout:SCLTimeoutConfiguration?=nil, colorStyle: UInt?=0x000000, colorTextButton: UInt=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
return showTitle(title, subTitle: subTitle, timeout:timeout, completeText:closeButtonTitle, style: style, colorStyle: colorStyle, colorTextButton: colorTextButton, circleIconImage: circleIconImage, animationStyle: animationStyle)
}
// showTitle(view, title, subTitle, timeout, style)
@discardableResult
open func showTitle(_ title: String, subTitle: String? = nil, timeout: SCLTimeoutConfiguration?, completeText: String?, style: SCLAlertViewStyle, colorStyle: UInt?=0x000000, colorTextButton: UInt?=0xFFFFFF, circleIconImage: UIImage? = nil, animationStyle: SCLAnimationStyle = .topToBottom) -> SCLAlertViewResponder {
selfReference = self
view.alpha = 0
view.tag = uniqueTag
view.accessibilityIdentifier = uniqueAccessibilityIdentifier
let rv = UIApplication.shared.keyWindow! as UIWindow
rv.addSubview(view)
view.frame = rv.bounds
baseView.frame = rv.bounds
// Alert colour/icon
var iconImage: UIImage?
let colorInt = colorStyle ?? style.defaultColorInt
viewColor = UIColorFromRGB(colorInt)
// Icon style
switch style {
case .success:
iconImage = checkCircleIconImage(circleIconImage, defaultImage: SCLAlertViewStyleKit.imageOfCheckmark)
case .error:
iconImage = checkCircleIconImage(circleIconImage, defaultImage: SCLAlertViewStyleKit.imageOfCross)
case .notice:
iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfNotice)
case .warning:
iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfWarning)
case .info:
iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfInfo)
case .edit:
iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfEdit)
case .wait:
iconImage = nil
case .question:
iconImage = checkCircleIconImage(circleIconImage, defaultImage:SCLAlertViewStyleKit.imageOfQuestion)
case .none:
iconImage = nil
}
// Title
if !title.isEmpty {
self.labelTitle.text = title
let actualHeight = title.heightWithConstrainedWidth(width: subViewsWidth, font: self.labelTitle.font)
self.labelTitle.frame = CGRect(x:appearance.margin.horizontal, y:appearance.margin.titleTop, width: subViewsWidth, height:actualHeight)
}
// Subtitle
if let subTitle = subTitle,
!subTitle.isEmpty {
viewText.text = subTitle
// Adjust text view size, if necessary
let str = subTitle as NSString
let attr = [NSAttributedString.Key.font:viewText.font ?? UIFont()]
let sz = CGSize(width: subViewsWidth, height:90)
let r = str.boundingRect(with: sz, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attr, context:nil)
let ht = ceil(r.size.height)
if ht < appearance.kTextHeight {
appearance.kWindowHeight -= (appearance.kTextHeight - ht)
appearance.setkTextHeight(ht)
}
}
// Done button
if appearance.showCloseButton {
// Retrieves the "done" word translated using Apple's UIKit dictionary
let localizedDone = Bundle(for: UIApplication.self).localizedString(forKey: "Done", value: nil, table: nil)
_ = addButton(completeText ?? localizedDone, target:self, selector:#selector(SCLAlertView.hideView))
}
//hidden/show circular view based on the ui option
circleView.isHidden = !appearance.showCircularIcon
circleBG.isHidden = !appearance.showCircularIcon
// Alert view colour and images
circleView.backgroundColor = viewColor
// Spinner / icon
if style == .wait {
let indicator = UIActivityIndicatorView(style: appearance.activityIndicatorStyle)
indicator.startAnimating()
circleIconView = indicator
}
else {
if let iconTintColor = iconTintColor {
circleIconView = UIImageView(image: iconImage!.withRenderingMode(.alwaysTemplate))
circleIconView?.tintColor = iconTintColor
}
else {
circleIconView = UIImageView(image: iconImage!)
}
}
circleView.addSubview(circleIconView!)
let x = (appearance.kCircleHeight - appearance.kCircleIconHeight) / 2
circleIconView!.frame = CGRect( x: x, y: x, width: appearance.kCircleIconHeight, height: appearance.kCircleIconHeight)
circleIconView?.layer.masksToBounds = true
for txt in inputs {
txt.layer.borderColor = viewColor.cgColor
}
for txt in input {
txt.layer.borderColor = viewColor.cgColor
}
for btn in buttons {
if let customBackgroundColor = btn.customBackgroundColor {
// Custom BackgroundColor set
btn.backgroundColor = customBackgroundColor
} else {
// Use default BackgroundColor derived from AlertStyle
btn.backgroundColor = viewColor
}
if let customTextColor = btn.customTextColor {
// Custom TextColor set
btn.setTitleColor(customTextColor, for: .normal)
} else {
// Use default BackgroundColor derived from AlertStyle
btn.setTitleColor(UIColorFromRGB(colorTextButton ?? 0xFFFFFF), for: .normal)
}
}
// Adding timeout
if let timeout = timeout {
self.timeout = timeout
timeoutTimer?.invalidate()
timeoutTimer = Timer.scheduledTimer(timeInterval: timeout.value, target: self, selector: #selector(SCLAlertView.hideViewTimeout), userInfo: nil, repeats: false)
showTimeoutTimer?.invalidate()
showTimeoutTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SCLAlertView.updateShowTimeout), userInfo: nil, repeats: true)
}
// Animate in the alert view
self.showAnimation(animationStyle)
// Chainable objects
return SCLAlertViewResponder(alertview: self)
}
// Show animation in the alert view
fileprivate func showAnimation(_ animationStyle: SCLAnimationStyle = .topToBottom, animationStartOffset: CGFloat = -400.0, boundingAnimationOffset: CGFloat = 15.0, animationDuration: TimeInterval = 0.2) {
let rv = UIApplication.shared.keyWindow! as UIWindow
var animationStartOrigin = self.baseView.frame.origin
var animationCenter : CGPoint = rv.center
switch animationStyle {
case .noAnimation:
self.view.alpha = 1.0
return;
case .topToBottom:
animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: self.baseView.frame.origin.y + animationStartOffset)
animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y + boundingAnimationOffset)
case .bottomToTop:
animationStartOrigin = CGPoint(x: animationStartOrigin.x, y: self.baseView.frame.origin.y - animationStartOffset)
animationCenter = CGPoint(x: animationCenter.x, y: animationCenter.y - boundingAnimationOffset)
case .leftToRight:
animationStartOrigin = CGPoint(x: self.baseView.frame.origin.x + animationStartOffset, y: animationStartOrigin.y)
animationCenter = CGPoint(x: animationCenter.x + boundingAnimationOffset, y: animationCenter.y)
case .rightToLeft:
animationStartOrigin = CGPoint(x: self.baseView.frame.origin.x - animationStartOffset, y: animationStartOrigin.y)
animationCenter = CGPoint(x: animationCenter.x - boundingAnimationOffset, y: animationCenter.y)
}
self.baseView.frame.origin = animationStartOrigin
if self.appearance.dynamicAnimatorActive {
UIView.animate(withDuration: animationDuration, animations: {
self.view.alpha = 1.0
})
self.animate(item: self.baseView, center: rv.center)
} else {
UIView.animate(withDuration: animationDuration, animations: {
self.view.alpha = 1.0
self.baseView.center = animationCenter
}, completion: { finished in
UIView.animate(withDuration: animationDuration, animations: {
self.view.alpha = 1.0
self.baseView.center = rv.center
})
})
}
}
// DynamicAnimator function
var animator : UIDynamicAnimator?
var snapBehavior : UISnapBehavior?
fileprivate func animate(item : UIView , center: CGPoint) {
if let snapBehavior = self.snapBehavior {
self.animator?.removeBehavior(snapBehavior)
}
self.animator = UIDynamicAnimator.init(referenceView: self.view)
let tempSnapBehavior = UISnapBehavior.init(item: item, snapTo: center)
self.animator?.addBehavior(tempSnapBehavior)
self.snapBehavior? = tempSnapBehavior
}
//
@objc open func updateShowTimeout() {
guard let timeout = self.timeout else {
return
}
self.timeout?.value = timeout.value.advanced(by: -1)
for btn in buttons {
guard let showTimeout = btn.showTimeout else {
continue
}
let timeoutStr: String = showTimeout.prefix + String(Int(timeout.value)) + showTimeout.suffix