summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/RelayStatusIndicatorView.swift
blob: ab8626001eb7bc244bd80212c5cc13ce16c66674 (plain)
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
//
//  RelayStatusIndicatorView.swift
//  MullvadVPN
//
//  Created by pronebird on 01/05/2019.
//  Copyright © 2019 Mullvad VPN AB. All rights reserved.
//

import UIKit

@IBDesignable class RelayStatusIndicatorView: UIControl {

    private let circleLayer: CALayer = {
        let layer = CALayer()
        layer.needsDisplayOnBoundsChange = true
        return layer
    }()

    @IBInspectable var isActive: Bool = false {
        didSet {
            updateCircleLayerColor()
        }
    }

    override var isHighlighted: Bool {
        didSet {
            updateCircleLayerColor()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        updateCircleLayerColor()
    }

    override func layoutSublayers(of layer: CALayer) {
        super.layoutSublayers(of: layer)

        guard layer == self.layer else { return }

        // keep the circular layer square
        let shortSide = min(layer.bounds.width, layer.bounds.height)
        let circleOrigin = CGPoint(
            x: (layer.bounds.width - shortSide) * 0.5,
            y: (layer.bounds.height - shortSide) * 0.5
        )
        let circleSize = CGSize(width: shortSide, height: shortSide)

        circleLayer.frame = CGRect(origin: circleOrigin, size: circleSize)
        circleLayer.cornerRadius = shortSide * 0.5
    }

    private func setup() {
        isUserInteractionEnabled = false
        backgroundColor = UIColor.clear

        layer.addSublayer(circleLayer)
        updateCircleLayerColor()
    }

    private func updateCircleLayerColor() {
        let baseColor = isActive
            ? UIColor.RelayStatusIndicator.activeColor
            : UIColor.RelayStatusIndicator.inactiveColor

        let circleColor: UIColor = isHighlighted ? tintColor : baseColor

        CATransaction.begin()
        CATransaction.setDisableActions(true)
        circleLayer.backgroundColor = circleColor.cgColor
        CATransaction.commit()
    }
}