-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilities.swift
266 lines (214 loc) · 8.27 KB
/
Utilities.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
//
// Utilities.swift
// On The Fly
//
// Created by Scott Higgins on 1/24/17.
// Copyright © 2017 ScottieH. All rights reserved.
//
import Foundation
import UIKit
// MARK: - UIViewController Extensions
// Allows the project to enable feature of dismissing keyboard whenever the user taps the screen anywhere
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
// easily present pop-up alerts
func alert(message: String, title: String = "") {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
func alertDismissView(message: String, title: String = "") {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: { action in
self.dismiss(animated: true, completion: nil)
})
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion: nil)
}
}
// MARK: - UITextField Extensions
// Auto-round the corner of the TextField boxes
extension UITextField {
func roundCorners() {
self.layer.borderWidth = 2.0
self.layer.cornerRadius = 8.0
}
}
//MARK: - String Extensions
// Use regular expression matching to check for a valid email
extension String {
func isValidEmail() -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
mutating func trimTrailingWhitespace() {
if let trailingWs = self.range(of: "\\s+$", options: .regularExpression) {
self.replaceSubrange(trailingWs, with: "")
}
if let leadingWs = self.range(of: "\\s+^", options: .regularExpression) {
self.replaceSubrange(leadingWs, with: "")
}
}
}
// MARK: - UIButton Extensions
extension UIButton {
func changeImageAnimated(image: UIImage?) {
guard let imageView = self.imageView, let currentImage = imageView.image, let newImage = image else {
return
}
let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents")
crossFade.duration = 0.5
crossFade.fromValue = currentImage.cgImage
crossFade.toValue = newImage.cgImage
crossFade.isRemovedOnCompletion = false
crossFade.fillMode = kCAFillModeForwards
imageView.layer.add(crossFade, forKey: "animateContents")
}
func addBlackBorder() {
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor.black.cgColor
}
}
// MARK: - UILabel Extensions
extension UILabel {
func setSizeFont (sizeFont: Double) {
self.font = UIFont(name: self.font.fontName, size: CGFloat(sizeFont))!
self.sizeToFit()
}
}
// MARK: - UIColor Extensions
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
// MARK: - Double Extensions
extension Double {
/// Rounds the double to decimal places value
func roundTo(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
// MARK: - Flight Validation Errors
enum FlightErrors: Error {
case tooHeavyOnRamp
case invalidCenterOfGravity
case invalidTakeoffCog
case invalidLandingCog
case noStartingFuel
case insufficientFuel
}
// MARK: - Password Strength Checker
enum PasswordStrength: Int {
case None
case Weak
case Moderate
case Strong
static func checkStrength(password: String) -> PasswordStrength {
let len: Int = password.characters.count
var strength: Int = 0
switch len {
case 0:
return .None
case 1...4:
strength += 1
case 5...8:
strength += 2
default:
strength += 3
}
// Upper case, Lower case, Number & Symbols
let patterns = ["^(?=.*[A-Z]).*$", "^(?=.*[a-z]).*$", "^(?=.*[0-9]).*$",
"^(?=.*[!@#%&-_=:;\"'<>,`~\\*\\?\\+\\[\\]\\(\\)\\{\\}\\^\\$\\|\\\\\\.\\/]).*$"]
for pattern in patterns {
if password.range(of: pattern, options: .regularExpression) != nil {
strength += 1
}
}
switch strength {
case 0:
return .None
case 1...3:
return .Weak
case 4...6:
return .Moderate
default:
return .Strong
}
}
}
// MARK: - Style struct
struct Style{
// MARK: ToDo Fix Colors and Font Sizes
static var sectionHeaderTitleFont = UIFont(name: "Helvetica-Bold", size: 20)
static var sectionHeaderTitleColor = UIColor.white
static var sectionHeaderBackgroundColor = UIColor.black
static var sectionHeaderBackgroundColorHighlighted = UIColor.gray
static var sectionHeaderAlpha: CGFloat = 1.0
static var mainBackgroundColor = UIColor(netHex: 0x4A75FF)
static var darkBlueAccentColor = UIColor(netHex: 0x0036e6)
static var greenAccentColor = UIColor(netHex: 0x35DB32)
// MARK: ToDO Implement theme selection
// http://sdbr.net/post/Themes-in-Swift/
}
// MARK: - Android Toast-styled Messages
class Toast
{
class private func showAlert(backgroundColor:UIColor, textColor:UIColor, message:String)
{
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
let label = UILabel(frame: CGRect.zero)
label.textAlignment = NSTextAlignment.center
label.text = message
label.font = UIFont(name: "", size: 15)
label.adjustsFontSizeToFitWidth = true
label.backgroundColor = backgroundColor
label.textColor = textColor
label.sizeToFit()
label.numberOfLines = 4
label.layer.shadowColor = UIColor.gray.cgColor
label.layer.shadowOffset = CGSize(width: 4, height: 3)
label.layer.shadowOpacity = 0.3
label.frame = CGRect(x: appDelegate.window!.frame.size.width, y: 64, width: appDelegate.window!.frame.size.width, height: 44)
label.alpha = 1
appDelegate.window!.addSubview(label)
var basketTopFrame: CGRect = label.frame;
basketTopFrame.origin.x = 0;
UIView.animate(withDuration
:1.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
label.frame = basketTopFrame
}, completion: {
(value: Bool) in
UIView.animate(withDuration:2.0, delay: 2.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
label.alpha = 0
}, completion: {
(value: Bool) in
label.removeFromSuperview()
})
})
}
class func showPositiveMessage(message:String)
{
showAlert(backgroundColor: UIColor.green, textColor: UIColor.white, message: message)
}
class func showNegativeMessage(message:String)
{
showAlert(backgroundColor: UIColor.red, textColor: UIColor.white, message: message)
}
}