AutolayoutViewController.swift 11.7 KB
Newer Older
Davide De Rosa's avatar
Davide De Rosa committed
1
2
3
4
5
6
7
8
9
//
//  AutolayoutViewControllers.swift
//  PIALibrary-iOS
//
//  Created by Davide De Rosa on 10/20/17.
//  Copyright © 2017 London Trust Media. All rights reserved.
//

import UIKit
10
import Lottie
Davide De Rosa's avatar
Davide De Rosa committed
11
12
13
14
15
16
17
18
19
/// Declares a generic, dismissable modal controller.
public protocol ModalController: class {

    /**
     Dismisses the modal controller.
     */
    func dismissModal()
}

20
21
22
23
24
public protocol AnimatingLoadingDelegate: class {
    func showLoadingAnimation()
    func hideLoadingAnimation()
}

Jose Blaya's avatar
Jose Blaya committed
25
26
27
28
29
30
31
/// Enum used to determinate the status of the view controller and apply effects over the UI elements
public enum ViewControllerStatus {
    case initial
    case restore(element: UIView)
    case error(element: UIView)
}

Davide De Rosa's avatar
Davide De Rosa committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/// Base view controller with dynamic constraints and restyling support.
///
/// - Seealso: `Theme`
open class AutolayoutViewController: UIViewController, ModalController, Restylable {

    /// The outlet to the main view container (optional).
    ///
    /// - Seealso: `ThemeStrategy.autolayoutContainerMargins(for:)`
    @IBOutlet public weak var viewContainer: UIView?

    /// :nodoc:
    open override var preferredStatusBarStyle: UIStatusBarStyle {
        return Theme.current.statusBarAppearance(for: self)
    }
    
Jose Blaya's avatar
Jose Blaya committed
47
48
49
50
51
52
    /// The initial status of the view controller. Every time the var changes the value, we reload the UI of the form element given as parameter.
    /// Example of use: self.status = .error(element: textEmail)
    open var status: ViewControllerStatus = .initial {
        didSet { reloadFormElements() }
    }
    
Davide De Rosa's avatar
Davide De Rosa committed
53
54
55
56
57
58
59
60
61
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// :nodoc:
    open override func viewDidLoad() {
        super.viewDidLoad()

        if let viewContainer = viewContainer {
Jose Blaya's avatar
Jose Blaya committed
62
            Theme.current.applyPrincipalBackground(viewContainer)
Davide De Rosa's avatar
Davide De Rosa committed
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
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(viewShouldRestyle), name: .PIAThemeDidChange, object: nil)
        viewShouldRestyle()
    }
    
    /// :nodoc:
    open override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        refreshOrientationConstraints(size: view.bounds.size)
    }
    
    private func refreshOrientationConstraints(size: CGSize) {
        if let viewContainer = viewContainer {
            let orientation: UIInterfaceOrientationMask = (isLandscape ? .landscape : .portrait)
            viewContainer.layoutMargins = Theme.current.autolayoutContainerMargins(for: orientation)
        }
        didRefreshOrientationConstraints()
    }

    // MARK: Public interface

    /// Shortcut for signalling landscape orientation.
    public var isLandscape: Bool {
        return (view.bounds.size.width > view.bounds.size.height)
    }

    /**
     Called right after refreshing the orientation contraints, e.g. when the device rotates.
     */
    open func didRefreshOrientationConstraints() {
    }
    
    // MARK: ModalController
    
    /// :nodoc:
    @objc open func dismissModal() {
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: Restylable
    
    /// :nodoc:
    @objc open func viewShouldRestyle() {
        Theme.current.applyNavigationBarStyle(to: self)
Jose Blaya's avatar
Jose Blaya committed
109
        Theme.current.applyPrincipalBackground(view)
Davide De Rosa's avatar
Davide De Rosa committed
110
        if let viewContainer = viewContainer {
Jose Blaya's avatar
Jose Blaya committed
111
            Theme.current.applyPrincipalBackground(viewContainer)
Davide De Rosa's avatar
Davide De Rosa committed
112
113
114
        }
        setNeedsStatusBarAppearanceUpdate()
    }
Jose Blaya's avatar
Jose Blaya committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    
    private func reloadFormElements() {
        switch status {
        case .initial:
            break
        case .restore(let element):
            restoreFormElementBorder(element)
        case .error(let element):
            updateFormElementBorder(element)
        }
    }
    
    private func restoreFormElementBorder(_ element: UIView) {
        if let element = element as? UITextField {
            Theme.current.applyInput(element)
Jose Blaya's avatar
Jose Blaya committed
130
            element.rightView = nil
Jose Blaya's avatar
Jose Blaya committed
131
132
133
134
135
136
        }
    }
    
    private func updateFormElementBorder(_ element: UIView) {
        if let element = element as? UITextField {
            Theme.current.applyInputError(element)
Jose Blaya's avatar
Jose Blaya committed
137
138
139
            let iconWarning = UIImageView(image:Asset.iconWarning.image.withRenderingMode(.alwaysTemplate))
            iconWarning.tintColor = .piaRed
            element.rightView = iconWarning
Jose Blaya's avatar
Jose Blaya committed
140
141
        }
    }
142
143
144
145
146
147
148
149
150
151
    
    public func styleNavigationBarWithTitle(_ title: String) {
        
        let currentStatus = Client.providers.vpnProvider.vpnStatus
        
        switch currentStatus {
        case .connected:
            let titleLabelView = UILabel(frame: CGRect.zero)
            titleLabelView.style(style: TextStyle.textStyle6)
            titleLabelView.text = title
Jose Blaya's avatar
Jose Blaya committed
152
153
154
155
156
157
            if let navController = navigationController {
                Theme.current.applyCustomNavigationBar(navController.navigationBar,
                                                       withTintColor: .white,
                                                       andBarTintColors: [UIColor.piaGreen,
                                                                          UIColor.piaGreenDark20])
            }
Jose Blaya's avatar
Jose Blaya committed
158
            let size = titleLabelView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
Jose Blaya's avatar
Jose Blaya committed
159
            titleLabelView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
160
161
162
163
164
165
166
167
168
            navigationItem.titleView = titleLabelView
            setNeedsStatusBarAppearanceUpdate()
            
        default:
            let titleLabelView = UILabel(frame: CGRect.zero)
            titleLabelView.style(style: Theme.current.palette.appearance == .dark ?
                TextStyle.textStyle6 :
                TextStyle.textStyle7)
            titleLabelView.text = title
Jose Blaya's avatar
Jose Blaya committed
169
170
171
172
173
174
            if let navigationController = navigationController {
                Theme.current.applyCustomNavigationBar(navigationController.navigationBar,
                                                       withTintColor: nil,
                                                       andBarTintColors: nil)
            }
            
Jose Blaya's avatar
Jose Blaya committed
175
            let size = titleLabelView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
Jose Blaya's avatar
Jose Blaya committed
176
            titleLabelView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
177
178
179
180
181
182
            navigationItem.titleView = titleLabelView
            setNeedsStatusBarAppearanceUpdate()
            
        }
    }

183
184
185
    @objc public func back(_ sender: Any?) {
        self.navigationController?.popViewController(animated: true)
    }
Jose Blaya's avatar
Jose Blaya committed
186

Davide De Rosa's avatar
Davide De Rosa committed
187
}
188

189
190
191
192
193
194
195
196
197
198
//MARK: - iOS13 Dark mode
extension AutolayoutViewController {
    
    override open func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        Macros.postNotification(.PIAThemeShouldChange)
    }
    
}

199
200
201
extension AutolayoutViewController: AnimatingLoadingDelegate {
    
    private struct LottieRepos {
Jose Blaya's avatar
Jose Blaya committed
202
        static var graphLoad: AnimationView?
203
204
205
        static var containerView: UIView?
    }
    
Jose Blaya's avatar
Jose Blaya committed
206
    var graphLoad: AnimationView? {
207
        get {
Jose Blaya's avatar
Jose Blaya committed
208
            return objc_getAssociatedObject(self, &LottieRepos.graphLoad) as? AnimationView
209
210
211
        }
        set {
            if let unwrappedValue = newValue {
Jose Blaya's avatar
Jose Blaya committed
212
                objc_setAssociatedObject(self, &LottieRepos.graphLoad, unwrappedValue as AnimationView?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
            }
        }
    }

    var containerView: UIView? {
        get {
            return LottieRepos.containerView
        }
        set {
            if let unwrappedValue = newValue {
                LottieRepos.containerView = unwrappedValue
            }
        }
    }

    public func showLoadingAnimation() {
        if graphLoad == nil {
230
            containerView = UIView(frame: UIScreen.main.bounds)
Jose Blaya's avatar
Jose Blaya committed
231
232
233
            containerView?.backgroundColor = Theme.current.palette.appearance == .dark ?
                UIColor.black.withAlphaComponent(0.72) :
                UIColor.piaGrey1.withAlphaComponent(0.75)
Jose Blaya's avatar
Jose Blaya committed
234
            graphLoad = AnimationView(name: "pia-spinner")
235
236
237
238
239
        }
        addLoadingAnimation()
    }
    
    private func addLoadingAnimation() {
Jose Blaya's avatar
Jose Blaya committed
240
        graphLoad?.loopMode = .loop
241
242
        if let graphLoad = graphLoad,
            let containerView = containerView {
243
244
245
246
            if let key = self.navigationController?.view {
                key.addSubview(containerView)
                key.addSubview(graphLoad)
            }
Jose Blaya's avatar
Jose Blaya committed
247
            setLoadingConstraints()
248
249
250
251
252
253
254
255
256
257
            graphLoad.play()
        }
    }
    
    public func hideLoadingAnimation() {
        graphLoad?.stop()
        graphLoad?.removeFromSuperview()
        containerView?.removeFromSuperview()
    }
    
Jose Blaya's avatar
Jose Blaya committed
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
    private func setLoadingConstraints() {
        if let graphLoad = graphLoad,
            let keyView = self.navigationController?.view,
            let containerView = containerView {
             
            containerView.translatesAutoresizingMaskIntoConstraints = false
            graphLoad.translatesAutoresizingMaskIntoConstraints = false

            NSLayoutConstraint(item: containerView,
                               attribute: .left,
                               relatedBy: .equal,
                               toItem: keyView,
                               attribute: .left,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true

            NSLayoutConstraint(item: containerView,
                               attribute: .right,
                               relatedBy: .equal,
                               toItem: keyView,
                               attribute: .right,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true

            NSLayoutConstraint(item: containerView,
                               attribute: .top,
                               relatedBy: .equal,
                               toItem: keyView,
                               attribute: .top,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true

            NSLayoutConstraint(item: containerView,
                               attribute: .bottom,
                               relatedBy: .equal,
                               toItem: keyView,
                               attribute: .bottom,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true

            NSLayoutConstraint(item: graphLoad,
                               attribute: .centerX,
                               relatedBy: .equal,
                               toItem: containerView,
                               attribute: .centerX,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true
            
            NSLayoutConstraint(item: graphLoad,
                               attribute: .centerY,
                               relatedBy: .equal,
                               toItem: containerView,
                               attribute: .centerY,
                               multiplier: 1.0,
                               constant: 0.0).isActive = true
            
            let lottieWidth = UIScreen.main.bounds.width/4

            NSLayoutConstraint(item: graphLoad,
                               attribute: .width,
                               relatedBy: .equal,
                               toItem: nil,
                               attribute: .width,
                               multiplier: 1.0,
                               constant: lottieWidth).isActive = true
            
            NSLayoutConstraint(item: graphLoad,
                               attribute: .height,
                               relatedBy: .equal,
                               toItem: nil,
                               attribute: .height,
                               multiplier: 1.0,
                               constant: lottieWidth).isActive = true

        }
333
334
335
    }

}